python字符串之查找与替换_在Python中查找和替换文本
最簡單的查找替換
在Python中查找和替換非常簡單,如果當前對象是一個字符串str時,你可以使用該類型提供的find()或者index()方法查找指定的字符,如果能找到則會返回字符第一次出現的索引,如果不存在則返回-1。
>>> s = 'Cat and Dog'
>>> s.find('Dog')
8
>>> s.index('Dog')
8
>>> s.find('Duck')
-1
如果要替換目標字符串,用replace()方法就好了。
>>> s = 'Cat and Dog'
>>> s.replace('Cat', 'Dog')
'Dog and Dog'
通配符查找匹配
當然,如果你覺得上面的功能還不能滿足你,你想使用通配符來查找字符串?沒問題!fnmatch這個庫就能滿足你的要求,看例子!
>>> s = 'Cat and Dog'
>>> import fnmatch
>>> fnmatch.fnmatch(s,'Cat*')
True
>>> fnmatch.fnmatch(s,'C*and*D?')
False
>>> fnmatch.fnmatch(s,'C*and*D*')
True
正則表達式查找替換
如果你需要查找比較復雜的字符規則,正則表達式是你不二的選擇。下面是正則查找的簡單示例。
>>> import re
>>> s = 'We will fly to Thailand on 2016/10/31'
>>> pattern = r'\d+'
>>> re.findall(pattern, s)
['2016', '10', '31']
>>> re.search(pattern, s)
>>> re.search(pattern, s).group()
'2016'
接下來你可能需要用正則表達式去替換某些字符,那么你需要了解re.sub()方法,看例子。
>>> s = "I like {color} car."
>>> re.sub(r'\{color\}','blue',s)
'I like blue car.'
>>> s = 'We will fly to Thailand on 10/31/2016'
>>> re.sub('(\d+)/(\d+)/(\d+)', r'\3-\1-\2', s)
'We will fly to Thailand on 2016-10-31'
其實re.sub()遠比你相像的強大的多。在上面的例子里你可以替換類似于{color}這樣的模板字符,也可以把正則匹配到的所有分組調換順序,例如第二個例子一共匹配了3個分組,然后把第3個分組放到最前面 r'3-1-2',看明白了嗎?
接下來看另外一個例子。
s = "Tom is talking to Jerry."
name1 = "Tom"
name2 = "Jerry"
pattern = r'(.*)({0})(.*)({1})(.*)'.format(name1, name2)
print re.sub(pattern, r'\1\4\3\2\5', s)
# Jerry is talking to Tom.
其實你還可以自定義替換函數,也就是re.sub()的第二個參數。
def change_date(m):
from calendar import month_abbr
mon_name = month_abbr[int(m.group(1))]
return '{} {} {}'.format(m.group(2), mon_name, m.group(3))
s = 'We will fly to Thailand on 10/31/2016'
pattern = r'(\d+)/(\d+)/(\d+)'
print re.sub(pattern, change_date, s)
# We will fly to Thailand on 31 Oct 2016
最后給大家一個終極版的例子,里面用到了函數的閉包,著酸爽,你懂的!
def match_case(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
s = "LOVE PYTHON, love python, Love Python"
print re.sub('python', match_case('money'), s, flags=re.IGNORECASE)
# LOVE MONEY, love money, Love Money
寫在最后
其實正則表達式還有很多玩法,如果你想讓正則和通配符混合著用,一點問題都沒有,因為fnmatch還有一個translate()的方法,可以讓你把通配符無痛轉換成正則表達式,你愛怎么玩就怎么玩。
>>> fnmatch.translate('C*and*D*')
'C.*and.*D.*'
關于作者:Python技術愛好者,目前從事測試開發相關工作,轉載請注明原文出處。
歡迎關注我的博客 http://betacat.online,你可以到我的公眾號中去當吃瓜群眾。
總結
以上是生活随笔為你收集整理的python字符串之查找与替换_在Python中查找和替换文本的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android在线教学,基于Androi
- 下一篇: HbuilderX指定部分区域查找和替换