加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:31:11 所属栏目: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) 00000
我有一个文本文件,我想放入列表.

文本文件如下所示:

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','"#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','The Shawshank Redemption (1994)']

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读