5

I have a text file in which there are numbers in each line(only numbers). My color.txt looks like:

3
3
5
1
5
1
5

When I read this to list using

f=open('D:\\Emmanu\\project-data\\color.txt',"r")
    for line in f:
        g_colour_list.append(line.strip('\n'))
    print g_colour_list

the output is like

['3', '3', '5', '1', '5', '1', '5']

But I want it as:

[3,3,5,1,5,1,5]

How can I do that in the single line that is
g_colour_list.append(line.strip('\n'))?

martineau
  • 119,623
  • 25
  • 170
  • 301
Emmanu
  • 749
  • 3
  • 10
  • 26
  • So...you have a list of strings, and you want a list of integers. I bet you can find instructions for converting numeric strings to integers if you look for it. – larsks Apr 23 '16 at 12:46

5 Answers5

2

just cast your strings into integers:

g_colour_list.append(int(line.strip('\n')))
mvelay
  • 1,520
  • 1
  • 10
  • 23
1

Wrap a call to python's int function which converts a digit string to a number around your line.strip() call:

f=open('D:\\Emmanu\\project-data\\color.txt',"r")
    for line in f:
        g_colour_list.append(int(line.strip('\n')))
    print g_colour_list
1

One possible solution is to cast the string to integer on appending. You can do it this way :

g_colour_list.append(int(line.strip('\n')))

If you think you will get floats as well then you should use float() instead of int().

Julien Salinas
  • 1,059
  • 1
  • 10
  • 23
0
for line in f:
    g_colour_list.append(int(line.strip('\n')))

You can parse a string s to int with int(s)

Keiwan
  • 8,031
  • 5
  • 36
  • 49
0

You can typecast it to int, doing:

f = open('color.txt',"r")
g_colour_list=[]

for line in f:
    g_colour_list.append(int(line.strip('\n')))

print (g_colour_list)
fredmaggiowski
  • 2,232
  • 3
  • 25
  • 44
lakshman sai
  • 481
  • 6
  • 14