迭代具有不同可能字符的字符串

时间:2016-02-27 06:00:32

标签: python python-3.4

我刚刚在这里注册,因为我正在参加Python的在线课程,并且一直在使用这个网站来帮助我完成课程。我是;卡住了。

我没有发布我的实际作业,而只是我的代码中的一个元素,我正处于困难时期......

我正在尝试使用包含字母表中字母的列表来迭代字符串。我想让列表中的每个字母迭代不同索引处的单词。例如:

word =“熊猫” 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

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您的while循环仅适用于外for循环的第一次迭代,因为index未重置,并且在第一次完成后仍保留在len(word)。尝试将初始化它的行移动到外部循环内的0

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

答案 2 :(得分: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

你必须在forloop上重新初始化索引,只是为了重新开始单词

答案 3 :(得分: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

答案 4 :(得分:0)

您忘记在for循环中初始化索引计数器:

sys.argv[0]
相关问题