Patrick Vaillancourt
Patrick Vaillancourt

Reputation: 51

Iterating through a string with different possible characters

I just signed up here because I am taking an online course in Python and have been using this site to help me through the course. I am; however, stuck.

I am not posting my actual homework assignment, but rather just an element of my code I am having a difficult time with...

I am trying to iterate through a string using a list containing letters in the alphabet. I want to have each letter in the list iterate through the word at different indexes. For example:

word = "panda" char_list = ['a','b','c'] etc... Output should be aanda, panda, paada ...... Followed by banda,pbnda,pabda,...

My code iterates through the word using only the first character in the list. Sorry, I am super NEW to coding in general...

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

Upvotes: 4

Views: 151

Answers (5)

Rahul.M
Rahul.M

Reputation: 121

You just need to reset the index back to 0 after you are done iterating with each char .

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

Upvotes: 1

ml-moron
ml-moron

Reputation: 886

You forgot to initialise the index counter in the for loop:

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

Upvotes: 0

be_good_do_good
be_good_do_good

Reputation: 4441

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

you have to re-initialize index on the forloop, just to start all over again on the word

Upvotes: 1

Blckknght
Blckknght

Reputation: 104712

Your while loop only works for the first iteration of the outer for loop because index does not get reset and remains at len(word) after it finshes the first time. Try moving the line where you initialize it to 0 inside the outer loop:

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

Upvotes: 1

roadrunner66
roadrunner66

Reputation: 7941

You were very close. You just need to reset the index to zero. So after the for loop your first command should be index=0.

Upvotes: 1

Related Questions