2016-02-27 74 views
4

我刚刚在这里注册,因为我正在使用Python在线课程,并且一直在使用此网站来帮助我完成课程。我是;然而,卡住了。对具有不同可能字符的字符串进行迭代

我没有张贴我的实际家庭作业,而只是我的代码元素我有一个困难的时期......

我试图通过使用包含字母列表的字符串进行迭代字母。我想让列表中的每个字母在不同索引处遍历单词。例如:

字= “熊猫” char_list = [ 'A', 'B', 'C']等... 输出应aanda,熊猫,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 
+0

你忘了更新'index'计数器。在while循环之后将它设置为* 0 *。 – vaultah

回答

1

您的while循环仅适用于外部for循环的第一次循环,因为index未被重置并在第一次收缩后保持在len(word)。尝试移动,你把它初始化为0外环内线路:

for char in possible_chars: 
    index = 0 
    while index < len(word): 
     #... 
1

你是非常接近。 你只需要将索引重置为零。所以在for循环之后,你的第一个命令应该是index=0

1
index = 0 
word = "panda" 
possible_char = ['a', 'b', 'c', 'd', 'o'] 
for char in possible_char: 
    index = 0 
    while index < len(word): 
     new_word = word[:index] + char + word[index + 1:] 
     print (new_word) 
     index = index + 1 

您对for循环重新初始化索引,只是为了从头再来上的字

0

你忘了初始化for循环中的索引计数器:

index = 0 
word = "panda" 
possible_char = ['a', 'b', 'c', 'd', 'o'] 
for char in possible_char: 
    index = 0 
    while index < len(word): 
     new_word = word[:index] + char + word[index + 1:] 
     print (new_word) 
     index = index + 1 
1

您只需在完成迭代每个字符后将索引重置为0。

index = 0 
word = "panda" 
possible_char = ['a', 'b', 'c', 'd', 'o'] 
for char in possible_char: 
    index=0 
    while index < len(word): 
     new_word = word[:index] + char + word[index + 1:] 
     print (new_word) 
     index = index + 1