python 字符串替换

1.maketrans&translate

string.maketrans(instr,outstr)  返回一个翻译表 instr 和outstr 必须长度一致

bstr = astr.translate(strtable,delete),返回处理结果,strtable是替换规则,delete是删除的字符串

2.re,sub(pattern,repleced,string,max=0)

3.string.replace(old,new,max)

code:

#!/usr/bin/python
import string

from_str = "abcdefg"
to_str   = "1234567"
trantab = string.maketrans(from_str, to_str)
str = "this is string example....wow!!!";
#replace str
print str.translate(trantab);
#replace & delete str
print str.translate(trantab,"xm")

#string.replace
str = "this is string example....wow!!! this is really string";
print str.replace("is", "was");
print str.replace("is", "was", 3); 

#with re.sub
import re
phone = "2004-959-559 # This is Phone Number"
num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num 
num = re.sub(r'\D', "", phone)    
ub(pattern, repl, string, max=0)
    re.sub(pattern, repl, string, max=0)rint "Phone Num : ", num



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值