[英]Iterating through a string with different possible characters
我剛剛在這里報名,因為我正在參加Python的在線課程並且一直在使用這個網站來幫助我完成課程。 我是; 卡住了。
我沒有發布我的實際作業,而只是我的代碼的一個元素我很難與...
我試圖使用包含字母表中字母的列表迭代字符串。 我想讓列表中的每個字母迭代不同索引處的單詞。 例如:
word =“panda”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
你非常接近。 您只需將索引重置為零。 所以在for循環之后你的第一個命令應該是index=0
。
你的while
循環只適用於外部for
循環的第一次迭代,因為index
不會被重置並在第一次完成后保持在len(word)
。 嘗試將初始化的行移動到外部循環內的0
:
for char in possible_chars:
index = 0
while index < len(word):
#...
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上重新初始化索引,只是為了重新開始這個詞
在完成對每個char的迭代后,您只需將索引重置為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
你忘了在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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.