当前位置: 代码迷 >> 综合 >> Python replace() 和 re.sub() 字符串字符替换
  详细解决方案

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

热度:83   发布时间:2024-02-01 00:30:47.0

replace()

testStr = 'aa:bb[cc'

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

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

re.sub()

import re

testStr = 'aa:bb[cc}'

把 :[} 替换成 _

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

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

  相关解决方案