Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
替代python替换_Python - Fatal编程技术网

替代python替换

替代python替换,python,Python,我想知道下面的代码是否有替代方案,因为,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","0

我想知道下面的代码是否有替代方案,因为,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;

在这里,由于您只有1个字符的替换“键”,因此我将使用dict和
连接:

>>> 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'

这不会扩展到多个字符替换键,不过…

至少使用一个循环。第一位可以压缩为
{v:'{:02d}。enumerate(string.ascii_lowercase,1)}
中的k,v格式(k)或避免硬编码长列表。@DSM+1,把它放在答案中@DSM——是的,我已经考虑过了。但我不想把事情和OP最初的想法扯得太远