更改for循環中的word
變量不會更改word_list
中的字符串。你需要記住的索引並更新索引處的元素(以及從索引字) -
for i, word in enumerate(words_list):
for char in word:
if char in string.letters:
words_list[i] = words_list[i].replace(char, DICT_CODE.get(char))
演示 -
>>> words_list = ["bppx","xnt!"]
>>> DICT_CODE = {'b' : 'g', 'n' :'a', 'p' : 'o', 'x' : 'd', 't' : 'y'}
>>> for i, word in enumerate(words_list):
... for char in word:
... if char in string.letters:
... words_list[i] = words_list[i].replace(char, DICT_CODE.get(char))
>>> words_list
['good', 'day!']
但你一個更簡單的方法是要使用str.translate
(以及string.maketrans
)。示例 -
table = string.maketrans('bnpxt','gaody') #First argument characters in your original string, and second argument what they map to.
for i, word in enumerate(words_list):
words_list[i] = word.translate(table)
演示 -
>>> import string
>>> table = string.maketrans('bnpxt','gaody') #This creates the translation table
>>> words_list = ["bppx","xnt!"]
>>> for i, word in enumerate(words_list):
... words_list[i] = word.translate(table)
...
>>> print words_list
['good', 'day!']
此使用列表解析 -
words_list[:] = [word.translate(table) for word in words_list]
演示 -
>>> words_list = ["bppx","xnt!"]
>>> table = string.maketrans('bnpxt','gaody')
>>> words_list[:] = [word.translate(table) for word in words_list]
>>> words_list
['good', 'day!']
'打印word_list'將打印'word_list'你上面聲明。 – marmeladze
'[''.join(DICT_CODE.get(c,c)for c in s)for s in word_list]' –