Mika1996 Mika1996 - 1 year ago 90
Python Question

TypeError: unsupported operand type(s) for -: 'str' and 'int'

Right now my code will create a text file including the positions of each word in a sentence in a list, and each word in a list - like so: http://i.imgur.com/AY0gqcG.png?1

My code then opens back up the file and should be able to recreate the sentence using those positions and the words in the text file, but it doesn't seem to work with with the readlines code for some reason.

openfilename = open(openfilename,"r")
readlines = openfilename.readlines()

wordslist = readlines[0]
positionslist = readlines[1]


originalsentence = " ".join([wordslist[x-1] for x in positionslist])

For example this comes up with wordslist and positionslist coming out as:

[1, 2, 3, 2]
['test123', ',', '.']

Where as if I were to use:

positionslist = [1, 2, 3, 2]
wordslist = ['test123', ',', '.']
originalsentence = " ".join([wordslist[x-1] for x in positionslist])

It would work, and I have no idea why because, as a newcomer to python, you'd think they'd work the same. Looking at other people's post with the same error I'm supposedly missing a


line of code somewhere but I'm not sure where, or if that's even the problem.

Answer Source

Another solution is to use ast.literal_eval() to convert your string u'[1, 2, 3, 2] directly into a list of interger:

import ast

with open(openfilename, "r") as f:
    positionslist = ast.literal_eval(f.readline())
    wordslist = ast.literal_eval(f.readline())

    print(" ".join([wordslist[x-1] for x in positionslist]))

Also, the with statement replace a try and catch. It also automatically close the file after the block.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download