Python 字符替换

 

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)

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值