OpenSrcFTW
OpenSrcFTW

Reputation: 211

strip ' from all members in a list

Ok, so I converted each line in a text file into a member of a list by doing the following:
chkseq=[line.strip() for line in open("sequence.txt")]
So when I print chkseq I get this:
['3','3']
What I would like is for it to instead look like this:
[3,3]
I know this is possible, I'm just unsure of how! I need them to be intergers, not strings. So if all else fails, that is my main goal in this: create a list from a .txt file whose members are intergers (which would be all the .txt file contained).
Thanks!! -OSFTW

Upvotes: 0

Views: 181

Answers (4)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798566

Passing a string to the int constructor will attempt to turn it into a int.

>>> int('3')
3
>>> int('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'foo'

Upvotes: 0

Leif Andersen
Leif Andersen

Reputation: 22332

Say your array is called input, and you want to store the value in an array called chkseq, your code would be:

chkseq = [int(i) for i in input]

Or, if you wanted to do everything all in one line:

chkseq = [int(i.strip()) for i in open("sequence.txt")]

Upvotes: 0

ObscureRobot
ObscureRobot

Reputation: 7336

iterate over the elements of your list and print them out with your preferred formatting rather than relying on the default formatting when printing the whole list at once.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838116

It looks like you want to interpret the strings as integers. Use int to do this:

chkseq = [int(line) for line in open("sequence.txt")] 

It can also be written using map instead of a list comprehension:

chkseq = map(int, open("sequence.txt"))

Upvotes: 2

Related Questions