Python convert string to list of Int [duplicate]
I have a text file with multiple lines of numbers, Using the code below produces the result below
Code:
with open('servers.txt') as x:
b = [line.strip() for line in x]
Result:
['867121767826980894', '828966373161828373']
I need to convert this to below so 867121767826980894 is an int and 828966373161828373 also an int separated by comma's
[867121767826980894, 828966373161828373]
Solution 1:
Convert string to int with the int()
function:
mylist = [int(item) for item in mylist]
Now the list contains integers and not strings.
To be sure that no error occurs during conversion, use try-except
:
for x in range(0, len(mylist)):
try:
mylist[x] = int(mylist[x])
except:
print("Error while converting item %s" % x)
The better solution that fits for your case is this one:
with open('servers.txt') as x:
try:
b = [int(line.strip()) for line in x]
except:
print("Error while converting line", line)
Hope those solutions help you.