Converting a string into a list in Python

后端 未结 5 826
孤独总比滥情好
孤独总比滥情好 2021-01-12 01:06

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

5条回答
  •  攒了一身酷
    2021-01-12 01:24

    >>> open("myfile.txt").readlines()
    >>> lines = open("myfile.txt").readlines()
    >>> lines
    ['1000\n', '2000\n', '3000\n', '4000\n']
    >>> clean_lines = [x.strip() for x in lines]
    >>> clean_lines
    ['1000', '2000', '3000', '4000']
    

    Or, if you have a string already, use str.split:

    >>> myfile
    '1000\n2000\n3000\n4000\n'
    >>> myfile.splitlines()
    ['1000', '2000', '3000', '4000', '']
    

    You can remove the empty element with a list comprehension (or just a regular for loop)

    >>> [x for x in myfile.splitlines() if x != ""]
    ['1000', '2000', '3000', '4000']
    

提交回复
热议问题