我想知道下面的代码是否有替代品,因为,1:有错误,2:我不想经常这样做:
restring=string.replace("a","01").replace("b","02")...
可能替换的代码:
chars=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","t","s","u","v","w","x","y","z"]
numbs=["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26"]
string="test";
restring=string.replace(chars,numbs);
print restring;
答案 0 :(得分:3)
在这里,由于您只有1个字符替换“键”,我会使用dict和join
:
>>> chars=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","t","s","u","v","w","x","y","z"]
>>> numbs=["01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26"]
>>> d = dict(zip(chars,numbs))
>>> my_sentence = "foobar"
>>> ''.join(d.get(c,c) for c in my_sentence)
'061515020118'
虽然这不会缩放到多个字符替换键...