python - 在 Python 中将字符串拆分为列表

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

最佳答案

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

关于python - 在 Python 中将字符串拆分为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23559626/

相关文章:

python - 您可以设置屏幕尺寸并在没有显示器的情况下使用 pyautogui/selenium chrome 驱动程序吗

python - 在python中的多线程中,如何产生结果并返回线程值?

python - 使用部分路径名为变量提供完整路径?

python - Pandas - 迭代时重复行

split - 从字符串中提取最后一个单词

perl - 如何使用 Perl 将字符串分成两部分?

python - 如果某个时间在某个时间范围内,则查找该时间并返回 Pandas 中的相应值?

c# - 在列表中添加新项目时出现奇怪的速度差异(C#)

python - 合并两个列表列表中的每个元素python

Java 数组上的多线程(分割)