我有一个要放入列表的文本文件。
文本文件如下所示:
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
参数:
>>> 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/