-10

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]
  • 5
    Call `int()` in your comprehension. – msanford Jan 10 '22 at 15:39
  • 2
    Nothing is separated by commas. That's just the string representation of a list. The list itself simply *contains* the values as separate objects, rather than "separating" them with anything. – chepner Jan 10 '22 at 15:56

3 Answers3

4

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.

Paul Kocian
  • 465
  • 4
  • 19
0

Look into this article : https://www.geeksforgeeks.org/python-converting-all-strings-in-list-to-integers/

for i in range(0, len(b)):
    b[i] = int(test_list[b])

OR

b = [int(i) for i in b]
Paul Kocian
  • 465
  • 4
  • 19
0

Or You could forego the whole problem and use the builtin csv reader to read the file as tsv, or well I guess ssv in this case

import csv
with open( "servers.txt" ) as f:
    csv.reader( f, delimiter=" " )