繁体   English   中英

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

[英]Split a string into a list in Python

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

文本文件如下所示:

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)']

split()接受一个可选的maxsplit参数:

在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)']

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

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

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

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

阅读文档

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

    #output ['0000000125', '1196672', '9.2', 'The Shawshank Redemption (1994)']
import re
s = input('Search: ').lower()
for ns in open("ratings.list.txt","rt"):
    if s in ns.lower():
        print(ns.split(maxsplit=3))

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

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

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

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

希望这可以帮助 : )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM