Python3字符串替换replace(),translate(),re.sub(),,Python3的字符
Python3字符串替换replace(),translate(),re.sub(),,Python3的字符
Python3的字符串替换,这里总结了三个函数,replace()和translate()和re.sub()
replace()
replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次
str.replace(old, new[, max])
a = ‘Hello,world. ByeBye!‘print(a.replace(‘l‘,‘Q‘))print(a.replace(‘abcdefghi‘,‘0123456789‘))print(a.replace(‘world‘,‘apple‘))
HeQQo,worQd. ByeBye!Hello,world. ByeBye!Hello,apple. ByeBye!
可见,replace()函数可以替换string中的单个字符,也可以替换连续的字符,但无法生成字符替换映射表
translate()
translate()函数也是python自带。与replace() 函数不同的是,这里使用str.maketrans函数来创建一个表,它可以使用各种参数,但是需要三个Arguments。
str.maketrans(‘‘,‘‘,del)
第一个参数为被替换的字符,第二个参数为替换的字符,第三个参数为要删除的字符
import stringa = ‘Hello,world. ByeBye!‘remove = string.punctuationtable = str.maketrans(‘abcdefgh‘,‘01234567‘,remove)print(a.translate(table))
H4lloworl3 By4By4
string.punctuation返回所有的标点符号,更多字符串常量如下图:
str.maketrans()的前两个参数相当于一个映射表,如上述结果,所有的‘e‘被替换成了‘4‘
第三个参数为要删除的字符,上述例子删除了所有的标点符号,如果要删除的字符还要加上空格的话,则可以这样:
table = str.maketrans(‘abcdefgh‘,‘01234567‘,remove+‘ ‘)print(a.translate(table))
H4lloworl3By4By4
re.sub()
这个是re库里的函数,其原型为re.sub(pattern, repl, string, count)
第一个参数为正则表达式需要被替换的参数,第二个参数是替换后的字符串,第三个参数为输入的字符串,第四个参数指替换个数。默认为0,表示每个匹配项都替换。
import rea = ‘Hello,world. ByeBye!‘print(re.sub(r‘[A-Z]‘, ‘8‘, a))
8ello,world. 8ye8ye!
上述例子是把所有的大写字母替换成8,下述表示只替换前2个这样的大写字母。
print(re.sub(r‘[A-Z]‘, ‘8‘, a, 2))
8ello,world. 8yeBye!Reference:Python3 replace()方法NLP-python3 translate()报错问题-TypeError: translate() takes exactly one argument (2 givenPython 标准库笔记:string模块关于python 的re.sub用法
Python3字符串替换replace(),translate(),re.sub()
相关内容
- python,appium,初步,,简介: 编程语言,
- python正则表达式re.match函数,,re.match 尝
- python (turtle)画五环,,实现代码:impor
- Python文件打开方式详解——r,w,a,r+,w+,a+,,r,r+,w,w+,
- python之网络编程,,TCP编程——htt
- python-1:Number数字类型 之二 相关函数 int.from_bytes,in
- python解析基于xml格式的日志文件,,大家中午好,由于过
- python网络爬虫高清PDF资料分享,,1、python+网
- Python之列表,,# list列表#
- IntelliJ IDEA下Java、Python实现Thrift调用,,终于跑通了!!
评论关闭