Python:字符串的替换--replace()、teanslate()、re.sub

一、replace()

replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次

str.replace(old, new[, max])

样式: 

a = 'Hello,world!'
print(a.replace('l','Q'))  # 把l换成Q 
print(a.replace('abcdefghi','0123456789'))  # 想把字符串中的a到i替换成0-9
print(a.replace('world','apple'))  # 把word替换为apple

 结果:

HeQQo,worQd!
Hello,world!  # 很明显,第二个没有执行(或者说没有替换)
Hello,apple!

原因:replace()函数可以替换string中的单个字符,也可以替换连续的字符,但无法生成字符替换映射表

二、translate()

translate()函数也是python自带。与replace() 函数不同的是,这里使用str.maketrans函数来创建一个表,它可以使用各种参数,但是需要三个Argumentsstr.

maketrans('','',del)  

第一个参数为被替换的字符,第二个参数为替换的字符,第三个参数为要删除的字符

使用:

stu_name = "学生1"
stu_name.translate(str.maketrans('', '', digits)) 
print(stu_name)  # 输出: 学生
import string
a = 'Hello,world!'
remove = string.punctuation  # 返回所有标点符号
table = str.maketrans('abcdefgh','01234567',remove)
print(a.translate(table))  # 输出:H4lloworl3

三、re.sub()

这个是re库里的函数,其原型为re.sub(pattern, repl, string, count)

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

例子: 

import re
a = 'Hello,world! HaHa'
print(re.sub(r'[A-Z]', '8', a))  # 8ello,world! 8a8a
print(re.sub(r'[A-Z]', '8', a, 2)) # 8ello,world! 8aHa 替换前2个

猜你喜欢

转载自blog.csdn.net/weixin_38676276/article/details/107515545