1

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;
4

1 に答える 1

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'

ただし、これは複数の文字置換キーには対応していません...

于 2013-03-08T20:36:39.217 に答える