Python replace() 和 re.sub() 字符串字符替换

Python replace() 和 re.sub() 字符串字符替换

replace()

testStr = 'aa:bb[cc'

testStr.replace(':','_')

每次只能替换一个字符或字符串

re.sub()

import re

testStr = 'aa:bb[cc}'

把 :[} 替换成 _

re.sub(r'[:[}]', '_', testStr)

re.sub() 的第一个参数是pattern,使用正则表达式,所以例子中 r'[:[}]' 代表 [] 中的任何一个字符,更多使用请另外学习正则表达式

原文地址:https://www.cnblogs.com/ibingshan/p/10332982.html