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