re.sub()替换功能
re.sub是个正则表达式方面的函数,用来实现通过正则表达式,实现比普通字符串的replace更加强大的替换功能。简单的替换功能可以使用replace()实现。
def main():
text = '123, word!'
text1 = text.replace('123', 'Hello')
print(text1)
if __name__ == '__main__':
main()
# Hello, wold!
如果通过re.sub(0函数则可以匹配任意的数字,并将其替换:
import re
def main():
content = 'abc124hello46goodbye67shit'
list1 = re.findall(r'\d+', content)
print(list1)
mylist = list(map(int, list1))
print(mylist)
print(sum(mylist))
print(re.sub(r'\d+[hg]', 'foo1', content))
print()
print(re.sub(r'\d+', '456654', content))
if __name__ == '__main__':
main()
# ['124', '46', '67']
# [124, 46, 67]
# 237
# abcfoo1ellofoo1oodbye67shit
# abc456654hello456654goodbye456654shit