1. 程式人生 > >python(字符串操作)

python(字符串操作)

2種 import 方法 python info 結果 style color pil

一、字符串的局部替換

python 字符串替換可以用2種方法實現:
1是用字符串本身的方法。
2用正則來替換字符串

下面用個例子來實驗下:
a = ‘hello word‘
我把a字符串裏的word替換為python
1用字符串本身的replace方法
a.replace(‘word‘,‘python‘)
輸出的結果是hello python

2用正則表達式來完成替換:
import re
strinfo = re.compile(‘word‘)
b = strinfo.sub(‘python‘,a)
print b
輸出的結果也是hello python

python(字符串操作)