Search code examples
pythonmatrix-indexing

Rewriting parts of a string inside an index


having a little bit of trouble indexing parts of a list in Python 3. The prompt/question is below and I have already made the input text file.

Prompt: You are given a file called class_scores.txt, where each line of the file contains a oneword username and a test score separated by spaces, like below:

GWashington 83
JAdams 86

Write code that scans through the file, adds 5 points to each test score, and outputs the usernames and new test scores to a new file, scores2.txt.

Here is the code I've written so far:

lines = [line.strip() for line in open('class_scores.txt')]
scores = [line.split(' ') for line in lines]
newScores = open('class_newScores.txt', 'w')

The trouble is, when I try to write new values to the scores, the index is the whole line of the word instead of the score so I can't change it.

Eg the index will output: GWashington 83

Instead of: 83

Thanks in advance for any assistance.


Solution

  • scores = [line.split(' ') for line in lines]
    

    will return you an array

    ['GWashington', '83']

    What you want is

    scores = [int(line.split(' ')[1]) for line in lines]
    

    which returns

    83

    so that you can do arithmetic manipulations