Python AttributeError: 对象没有属性“拆分”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29418281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:32:07  来源:igfitidea点击:

AttributeError: object has no attribute 'split'

pythonlist

提问by user3849475

There is an error,when I try to split

出现错误,当我尝试拆分时

l =[u'this is friday', u'holiday begin']
split_l =l.split()
print(split_l)

The error is:

错误是:

Traceback (most recent call last):
  File "C:\Users\spotify_track2.py", line 19, in <module>
    split_l =l.split()
AttributeError: 'list' object has no attribute 'split'

So I don't have idea to deal with this kind of error.

所以我不知道处理这种错误。

采纳答案by Bhargav Rao

Firstly, do not name your variable as list

首先,不要将您的变量命名为 list

Secondly listdoes not have the function splitIt is strwhich has it.

其次list是没有功能split它是str有它的。

Check the documentation for str.split

检查文档 str.split

Return a list of the words in the string, using sep as the delimiter string

返回字符串中单词的列表,使用 sep 作为分隔符字符串

(emphasis mine)

(强调我的)

So you need to do

所以你需要做

l =[u'this is friday', u'holiday begin']
split_list =[i.split() for i in l]
print(split_list)

Which would print

哪个会打印

[[u'this', u'is', u'friday'], [u'holiday', u'begin']]

Post Comment edit

发表评论编辑

To get what you expected you can try

为了得到你所期望的,你可以尝试

>>> l =[u'this is friday', u'holiday begin']
>>> " ".join(l).split(" ")
[u'this', u'is', u'friday', u'holiday', u'begin']

or as mentioned below

或如下所述

>>> [j for i in split_list for j in i]
[u'this', u'is', u'friday', u'holiday', u'begin']