Hello I am working on a project that exchanges random words with my predefined word.
But because I am a begginer at python I cant see what I am doing wrong.
I am getting this error message: 'My file destination' line 21, in <module> splitText[randomWord] = "TEST" IndexError: list assignment index out of range
line 21 is splitText[randomWord] = "TEST"
Code:
import random, math
stringText = ""
# Reading from file.txt
fileX = open('LoremIpsum.txt','r')
for line in fileX:
stringText = line
splitText = stringText.split()
fileX.close()
# Theoretical number of changed words
editedWords = math.floor(len(stringText) / 4)
# Trying to change the word at randomized index of the text
for specWord in range(editedWords):
randomWord = random.randrange(0,len(stringText)-1)
splitText[randomWord] = "TEST"
print(randomWord)
print(splitText)
CodePudding user response:
It's because you're using len(stringText)
to determine the range for the random numbers. stringText is a string, so its length will be the number of characters in it. That's way more than the length of splitText (which is a list of the words from stringText), because you have more characters than words in the string. It should work if you use len(splitText)-1
to calculcate the range of the random numbers.