Replace Items in List. - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Replace Items in List. (/thread-21604.html) |
Replace Items in List. - mcmxl22 - Oct-07-2019 I am trying to replace items in a list based on the index. I don't understand why I'm getting the 'index out of range' error. This is what I have: spaces = [] word = "word" guess = "o" spaces.append("'-'," * len(word)) letter_list = list(word) locate = letter_list.index(guess) print(spaces) spaces[locate] = guess print(spaces)This is the error: This is the desired output:
RE: Replace Items in List. - buran - Oct-07-2019 Your list has just one element, string. You need to fix line 4 RE: Replace Items in List. - mcmxl22 - Oct-07-2019 I changed line 4 to spaces = ['-' for letter in word] .I also got rid of line 1. It works! RE: Replace Items in List. - Larz60+ - Oct-07-2019 If you use exception testing, you can handle guess being incorrect: word = 'word' spaces = list('-' * len(word)) guess = 'o' try: locate = word.index(guess) spaces[locate] = guess print(f"{spaces}") except ValueError: print(f"guess {guess} not in word")output: you can put it all in a function to complete
|