Python3字符串替换replace(),translate(),re.sub()

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 string
a = 'Hello,world. ByeBye!'
remove = string.punctuation
table = 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)

扫描二维码关注公众号,回复: 854503 查看本文章

第一个参数为正则表达式需要被替换的参数,第二个参数是替换后的字符串,第三个参数为输入的字符串,第四个参数指替换个数。默认为0,表示每个匹配项都替换。

import re
a = '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:
  1. Python3 replace()方法
  2. NLP-python3 translate()报错问题-TypeError: translate() takes exactly one argument (2 given
  3. Python 标准库笔记:string模块
  4. 关于python 的re.sub用法

猜你喜欢

转载自www.cnblogs.com/bjwu/p/9038910.html