我刚刚在这里注册,因为我正在参加 Python 在线类(class),并且一直在使用这个网站来帮助我完成类(class)。我是;然而,卡住了。
我没有发布我的实际家庭作业,而只是我遇到困难的代码元素......
我正在尝试使用包含字母表中字母的列表来遍历字符串。我想让列表中的每个字母遍历不同索引处的单词。例如:
word = " Pandas " char_list = ['a','b','c'] 等等... 输出应该是aanda, panda, paada ...... 接着是banda,pbnda,pabda,...
我的代码只使用列表中的第一个字符遍历单词。 抱歉,我对一般的编码非常陌生......
index = 0
word = "panda"
possible_char = ['a', 'b', 'c', 'd', 'o']
for char in possible_char:
while index < len(word):
new_word = word[:index] + char + word[index + 1:]
print (new_word)
index = index + 1
最佳答案
您的 while
循环仅适用于外部 for
循环的第一次迭代,因为 index
不会重置并保持在 len(word)
第一次完成后。尝试将初始化它的行移动到外循环内的 0
:
for char in possible_chars:
index = 0
while index < len(word):
#...
关于python - 迭代具有不同可能字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35666323/