Zach Johnson
Zach Johnson

Reputation: 2237

How to convert string to int in python?

Hey guys todays my first day with python and im trying to do what seems like a simple thing to me but it keeps giving me errors. I am reading a number from a text file and trying to convert it into an int. This is my code:

f=open('commentcount.txt','r')
counts = f.readline()
int(counts)
counts = counts + 1
print(counts)

i am getting this error: counts = counts + 1 TypeError: Can't convert 'int' object to str implicitly

Can somone please tell me what I am doing wrong? thanks!

Upvotes: 2

Views: 425

Answers (1)

Christian Tapia
Christian Tapia

Reputation: 34146

You must assign the value of int(counts) to counts in order to keep changes. Note that int(...) doesn't modify the variable you pass in.

counts = int(counts)

Be sure that f.readline() return an string that "represents" a int.

Upvotes: 5

Related Questions