2013-03-08 233 views
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; 
+0

至少使用一個循環。 – 2013-03-08 20:33:59

回答

3

這裏,因爲你只有1個字符替換 「鑰匙」,我會用字典和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' 

雖然不會縮放到多個字符替換鍵...

+1

第一位可以被壓縮爲'{v:'{:02d}'。格式(k)爲k,v在枚舉中(string.ascii_lowercase,1)}'或者某個東西以避免對長列表進行硬編碼。 – DSM 2013-03-08 20:39:55

+0

謝謝你的工作。 – master101 2013-03-08 20:40:56

+0

@DSM +1,把它放在答案! – 2013-03-08 20:41:27