Reputation: 51
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
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
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
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
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
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