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