Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a string into a list in Python

Tags:

python

I have a text document that contains a list of numbers and I want to convert it to a list. Right now I can only get the entire list in the 0th entry of the list, but I want each number to be an element of a list. Does anyone know of an easy way to do this in Python?

1000
2000
3000
4000

to

['1000','2000','3000','4000']
like image 956
Sam Avatar asked Mar 30 '10 13:03

Sam


2 Answers

To convert a Python string into a list use the str.split method:

>>> '1000 2000 3000 4000'.split()
['1000', '2000', '3000', '4000']

split has some options: look them up for advanced uses.

You can also read the file into a list with the readlines() method of a file object - it returns a list of lines. For example, to get a list of integers from that file, you can do:

lst = map(int, open('filename.txt').readlines())

P.S: See some other methods for doing the same in the comments. Some of those methods are nicer (more Pythonic) than mine

like image 123
Eli Bendersky Avatar answered Oct 11 '22 03:10

Eli Bendersky


    $ cat > t.txt
    1
    2
    3
    4
    ^D
    $ python
    Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> l = [l.strip() for l in open('t.txt')]
    >>> l
    ['1', '2', '3', '4']
    >>> 
like image 26
rytis Avatar answered Oct 11 '22 04:10

rytis