python字符串替换re.sub()方法解析
2019-10-24 18:06
1871 查看
pattern可以是一个字符串也可以是一个正则,用于匹配要替换的字符,如果不写,字符串不做修改。\1 代表第一个分组
repl是将会被替换的值,repl可以是字符串也可以是一个方法。如果是一个字符串,反斜杠会被处理为逃逸字符,如\n会被替换为换行,等等。repl如果是一个function,每一个被匹配到的字段串执行替换函数。
\g<1> 代表前面pattern里面第一个分组,可以简写为\1,\g<0>代表前面pattern匹配到的所有字符串。
count是pattern被替换的最大次数,默认是0会替换所有。有时候可能只想替换一部分,可以用到count
实例1:
a = re.sub(r'hello', 'i love the', 'hello world') print(a)<br data-filtered="filtered">'i love the world' #hello world里面的hello被 i love the替换
实例2:
>>> a = re.sub(r'(\d+)', 'hello', 'my numer is 400 and door num is 200') >>> a 'my numer is hello and door num is hello' #数字400 和 200 被hello替换
实例3:
a = re.sub(r'hello (\w+), nihao \1', r'emma','hello sherry, nihao sherry') >>> a 'emma' #\1代表第一个分组的值即sherry,因为有两个sherry,所以用\1可以指代第二个,这样整个字符串被emma替换
示例4:
>>> a = re.sub('(\d{4})-(\d{2})-(\d{2})', r'\2-\3-\1', '2018-06-07') >>> a '06-07-2018' >>> a = re.sub('(\d{4})-(\d{2})-(\d{2})', r'\g<2>-\g<3>-\g<1>', '2018-06-07') >>> a '06-07-2018' #\2 和 \g<2> 指代的的都是前面的第二个分组
示例5:
import re def replace_num(str): numDict = {'0':'〇','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九'} print(str.group()) return numDict[str.group()] my_str = '2018年6月7号' a = re.sub(r'(\d)', replace_num, my_str) print(a) #每次匹配一个数字,执行函数,获取替换后的值
和sub()函数一样,只是返回的是一个tuple,替换后的字符串和替换的个数
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- python 正则字符串替换 re.sub 替换输入参数字符串inStrings 所有的一个或多个空格替换为newstring
- 用python中re.sub()替换文件中指定字符串
- Python:re.sub()实现字符串替换
- Python:re.sub()实现字符串替换
- python字符串替换之re.sub()
- python re.sub()替换正则的匹配内容方法
- python的re模块的sub方法
- python字符串替换的2种有效方法
- Python中json.loads()无法解析单引号字符串问题的两种解决方法
- python字符串内容替换的方法(转载)
- Python 正则 re.sub替换
- python同时替换多个字符串方法
- python_基础学习_03_正则替换文本(re.sub)
- python 从右到左字符串替换方法实现
- Python: 字符串搜索和匹配,re.compile() 编译正则表达式字符串,然后使用match() , findall() 或者finditer() 等方法
- python正则表达式替换re.sub使用
- python字符串替换方法和注意事项
- Python字符串拼接、截取及替换方法总结分析
- python的re模块的sub方法
- python字符串替换的2种有效方法