python - While loops list index out of range error. Strip off strings with double slases -
i wondering if me debug code. i'm curious why i'm getting list index out of range error. i'm trying add items in list , using number index list. in end, wanted strings in list cut off '//'.
word_list = [] = 0 while < len(word_list): word_list.extend(['he//llo', 'ho//w yo//u', 'be///gone']) += 1 word_list[i].strip('//') print(i) print(word_list[i]) print(i)
you condition never true i < len(word_list), i 0 , length of list never enter loop. cannot index empty list print(word_list[i]) i being 0 gives indexerror.
your next problem adding more items list in loop if did start loop infinite list size grow faster i, example adding single string list initially:
word_list = ["foo"] = 0 # never greater len(word_list) loops infinitely while < len(word_list): # never enter not < len(wordlist) print(i) word_list.extend(['he//llo', 'ho//w yo//u', 'be///gone']) += 1 word_list[i].strip('//') print(i) you add 3 elements list, increase i 1 equal infinite loop. not sure goal using while not seem want.
if wanted use loop replace / , have strings in list initially:
word_list = ['he//llo', 'ho//w yo//u', 'be///gone'] in range(len(word_list)): word_list[i] = word_list[i].replace("/","") print(i) strings immutable need reassign value, cannot change string inplace, above can become list comp:
word_list = ['he//llo', 'ho//w yo//u', 'be///gone'] word_list[:] = [s.replace("/","") s in word_list] i used str.replace strip removes start , end of strings.
Comments
Post a Comment