python中对字符串中的字符进行替换,首先想到的是
str.replace()
这对单个及少量字符的替换是比较方便的。例如,将所有的‘5’,‘0’,‘1’全部替换为‘S’,'O','I':
>>> x= "W0W! 1'm 5o good!"
>>> x.replace('0','O').replace('1','I').replace('5','S')
"WOW! I'm So good!"
但是如果需要替换的字符很多,那replace().replace().replace()....就会很长,很麻烦。
这是后可以选择 str.translate(),或者使用re.sub()
例如元音字符替换
Description:
Replace all vowel to exclamation mark in the sentence.
aeiouAEIOU
is vowel.Examples
replace("Hi!") === "H!!"
replace("!Hi! Hi!") === "!H!! H!!"
replace("aeiou") === "!!!!!"
replace("ABCDE") === "!BCD!"
1. 使用 str.translate(table[, deletechars])
str.translate()方法根据参数table给出的表(包含 256 个字符)转换字符串的字符, 要过滤掉的字符放到 del 参数中。
使用maketrans()生成用于替换的字典
def replace_exclamation(s):
return s.translate(str.maketrans('aeiouAEIOU', '!' * 10))
Python2.x版本中需要将maketrans方法从string中导入
from string import maketrans # Required to call maketrans function. intab = "aeiouAEIOU" outtab = '!'*10 #maketrans()要求intab和outtab长度一致,且一一对应 trantab = maketrans(intab, outtab)
Python3.x版本后,maketrans()成了内建函数str.maketrans(),无需从string中调用
2. 使用正则表达式
本例中,还可以用re.sub()函数
import re
def replace_exclamation(s):
return re.sub('[aeiouAEIOU]', '!', s)