Python3 - 字符串匹配和替换

问题

在字符串中匹配指定的文本模式并替换函数

解决方案

对于简单的字面模式,直接使用 str.replace() 方法便可,好比:spa

text = 'yeah, but no, but yeah, but no, but yeah'

print(text.replace('yeah', 'yep'))
yep, but no, but yep, but no, but yep

对于复杂的匹配,须要使用 re 模块中的 sub() 函数。 好比: 将11/27/2012 的日期字符串改为 2012-11-27 。示例以下:code

import re
text = 'Today is 11/27/2018. PyCon starts 3/13/2018.'
print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text))
Today is 2018-11-27. PyCon starts 2018-3-13.

sub() 函数中的第一个参数是匹配模式,第二个参数是替换模式。反斜杠数字指向匹配模式中的分组号。字符串

讨论

若是除了替换后的结果外,还想知道替换了多少次,可使用 re.subn() 来代替。好比:import

new_text, n = re.subn(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text)
print(new_text)
print(n)

Today is 2018-11-27. PyCon starts 2018-3-13.
2
相关文章
相关标签/搜索