python3 工作上遇到正则表达式

Python3 replace()方法

实例1

def main():
    text = 'python3, word!'
    text1 = text.replace('python3', 'Hello')
    print(text1)

if __name__ == '__main__':
    main()

以上实例输出结果如下:
Hello, wold!

实例2

#!/usr/bin/python3
str = "www.w3cschool.cc"
print ("菜鸟教程旧地址:", str)
print ("菜鸟教程新地址:", str.replace("w3cschool.cc", "runoob.com"))
str = "this is string example....wow!!!"
print (str.replace("is", "was", 3))

以上实例输出结果如下:

菜鸟教程旧地址: www.w3cschool.cc
菜鸟教程新地址: www.runoob.com
thwas was string example....wow!!!

re.sub()表示替换

实例1

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

猜你喜欢

转载自www.cnblogs.com/gqv2009/p/12675521.html