python中字符串操作--截取,查找,替換
python中,對字符串的操作是最常見的,python對字符串操作有自己特殊的處理方式。
字符串的截取
python中對于字符串的索引是比較特別的,來感受一下:
字符串的查找
查找當前字符串中,是否包含另外的字符串。
我們可以使用 index,或者find來進行查找,find和index的區別是,如果使用的是index的話,字符串查找中,如果找不到相應的字符串,會拋出一個ValueError的異常。
s = '123456789'
s.index('23')
#輸出:1
s.find('23')
#輸出:1
s.index('s')
#輸出
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
s.find('s')
#輸出 -1
分割字符串
總是有很多特殊字符,可以用來分割字符串。數據庫中經常把一組照片放在一個字段中,比如
img1.jpg@@@img2.jpg@@@img3.jpg
需要把不定長的照片都取出來,就需要同特殊字符把字符串分開,得到不同的照片。
分割的命令為split
s = 'img1.jpg@@@img2.jpg@@@img3.jpg'
s.split('@@@')
#結果為一個數值:['img1.jpg', 'img2.jpg', 'img3.jpg']
</code></pre>
### 字符串格式化
Python 支持格式化字符串的輸出 。盡管這樣可能會用到非常復雜的表達式,但最基本的用法是將一個值插入到一個有字符串格式符 %s 的字符串中。
在 Python 中,字符串格式化使用與 C 中 sprintf 函數一樣的語法。
<pre><code>
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21)
#以上實例輸出結果: My name is Zara and weight is 21 kg!
字符串Template化
在python中Template可以將字符串的格式固定下來,重復利用。
Template屬于string中的一個類,要使用他的話可以用以下方式調用:
from string import Template
我們使用以下代碼:
>>> s = Template('There ${moneyType} is ${money}')
>>> print s.substitute(moneyType = 'Dollar',money=12)
運行結果顯示“There Dollar is 12”
這樣我們就可以替換其中的數據了。
更多入門教程可以參考:[http://www.bugingcode.com/python_start/] (http://www.bugingcode.com/python_start/)
posted on 2018-01-12 16:04
漂漂 閱讀(228)
評論(0) 編輯 收藏 引用