将字符串拆分为Python中的列表

时间:2014-05-09 08:10:08

标签: python list split

我有一个我想要放入列表的文本文件。

文本文件如下所示:

New  Distribution  Votes  Rank  Title
     0000000125  1196672  9.2  The Shawshank Redemption (1994)
     0000000125  829707   9.2  The Godfather (1972)
     0000000124  547511   9.0  The Godfather: Part II (1974)
     0000000124  1160800  8.9   The Dark Knight (2008)

我尝试使用以下代码拆分列表:

x = open("ratings.list.txt","r")
movread = x.readlines()
x.close()


s = raw_input('Search: ')
for ns in movread:
    if s in ns:
        print(ns.split()[0:100])

输出:

      Search: #1 Single
     ['1000000103', '56', '6.3', '"#1', 'Single"', '(2006)']

但它没有给我想要的输出

它分裂标题之间的空格。

如何在不破坏标题的情况下将其拆分为列表?

预期产出:

 Search: #1 Single

  Distribution  Votes  Rank           Title
 ['1000000103', '56', '6.3', '"#1 Single" (2006)']

5 个答案:

答案 0 :(得分:10)

split()采用可选的maxsplit参数:

In Python 3

>>> s = "     0000000125  1196672  9.2  The Shawshank Redemption (1994)"
>>> s.split()
['0000000125', '1196672', '9.2', 'The', 'Shawshank', 'Redemption', '(1994)']
>>> s.split(maxsplit=3)
['0000000125', '1196672', '9.2', 'The Shawshank Redemption (1994)']

In Python 2,您需要将maxsplit参数指定为位置参数:

>>> s = "     0000000125  1196672  9.2  The Shawshank Redemption (1994)"
>>> s.split(None, 3)
['0000000125', '1196672', '9.2', 'The Shawshank Redemption (1994)']

答案 1 :(得分:1)

可能是你可以尝试使用re.split('你的模式,字符串),这应该根据你的正则表达式给你正确的列表。

import re
d = re.split('\s+',s,3)
print d

答案 2 :(得分:1)

阅读docs

  s = "     0000000125  1196672  9.2  The Shawshank Redemption (1994)"   
    print  s.split(None,3)

    #output ['0000000125', '1196672', '9.2', 'The Shawshank Redemption (1994)']

答案 3 :(得分:1)

import re
s = input('Search: ').lower()
for ns in open("ratings.list.txt","rt"):
    if s in ns.lower():
        print(ns.split(maxsplit=3))

答案 4 :(得分:0)

分裂的语法是: str.split([sep [,maxsplit]])

'sep'是用于分割字符串的分隔符(默认情况下,它匹配任何空格字符)
'maxsplit'参数可用于限制否。 Tim提到的分裂

如果您在列之间使用'\ t',则可以使用'\ t'作为分隔符

按照标准惯例,'\ t'用作列的分隔符,以便分割不会干扰字符串中的其他空格。此外,您使用的任何python版本都不存在任何兼容性问题。

希望这会有所帮助:)

相关问题