0

So I've been following along some of the projects from the 'Big Book of Small Python Projects' by Al Sweigart and ive been attempting to follow along one of the projects, however Ive been stuck on this segment of code for a while now and was wondering if anyone could help. Anytime i run the code I keep getting an error on this line "WORDS[i] = WORDS[i].strip().upper()". It says "'str' object does not support item assignment" and I am unsure how to fix. Any help is greatly appreciated.

# Load the WORDS list from the text file
with open('sevenletterwords.txt') as wordListFile:
    WORDS = wordListFile.readline()
    for i in range(len(WORDS)):
        # Convert each word to uppercase and remove the trailing newline
        WORDS[i] = WORDS[i].strip().upper()
2
  • Hello and welcome to StackOverflow! Is WORDS meant to be a single line? Commented Oct 13, 2022 at 21:07
  • 2
    WORDS is a string and cannot be assigned through indexing. Perhaps just use WORDS.upper().strip(), rather than the loop. Commented Oct 13, 2022 at 21:08

1 Answer 1

2

You need to use readlines:

with open('test.csv') as wordListFile:
    WORDS = wordListFile.readlines() # updated here
    for i in range(len(WORDS)):
        # Convert each word to uppercase and remove the trailing newline
        WORDS[i] = WORDS[i].strip().upper()

Here is an approach that uses a lambda function:

with open('test.csv') as wordListFile:
    WORDS = wordListFile.readlines()    
    WORDS = list(map(lambda x: x.strip().upper(), WORDS))
    print(WORDS)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.