我不太确定str.split(list, ' ')
和str.split(list, ' ')
之间的区别。
当我尝试编辑Learn Python The Hard Way - >
给出的代码时 1)阻挡ten_things = "Apples Oranges Crows Telephone Light Sugar"
stuff = str.split(ten_things, ' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
print "Let's check our list now. \n%s" % ten_things
while len(stuff) != 10:
next_one = more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "So there's %d items now." % len(stuff)
print "There we go: ", stuff
#我认为是正确的阻挡。
Wait there's not 10 things in that list, let's fix that.
Let's check our list now.
Apples Oranges Crows Telephone Light Sugar
Adding: Boy
So there's 7 items now.
Adding: Girl
So there's 8 items now.
Adding: Banana
So there's 9 items now.
Adding: Corn
So there's 10 items now.
There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
和结果--->
str.split("list, ' ' ")
2)ten_things = "Apples Oranges Crows Telephone Light Sugar"
stuff = str.split("ten_things, ' '")
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
print "Let's check our list now. \n%s" % ten_things
while len(stuff) != 10:
next_one = more_stuff.pop()
print "Adding: ", next_one
stuff.append(next_one)
print "So there's %d items now." % len(stuff)
#块可能有问题。
Wait there's not 10 things in that list, let's fix that.
Let's check our list now.
Apples Oranges Crows Telephone Light Sugar
Adding: Boy
So there's 4 items now. #why add from 4th item?
Adding: Girl
So there's 5 items now.
Adding: Banana
So there's 6 items now.
Adding: Corn
So there's 7 items now.
Adding: Frisbee
So there's 8 items now.
Adding: Song
So there's 9 items now.
Adding: Night
So there's 10 items now.
There we go: ['ten_things,', "'", "'", 'Boy', 'Girl', 'Banana', 'Corn', 'Frisbee', 'Song', 'Night']
我得到了--->
{{1}}
在ten_things中有6个项目,但是在2行的第5行中)_Result,为什么python从第4个添加项目?也不太了解最后一行打印的列表。 你能告诉我这些错误的原因吗? 非常感谢你!
答案 0 :(得分:0)
Python的split()
函数默认拆分如下:
如果未指定sep或为None,则应用不同的拆分算法:连续空格的运行被视为单个分隔符,如果字符串具有前导或尾随,则结果将在开头或结尾处不包含空字符串空格。
因此,如果您不提供参数,则会调用默认值。
在您的代码中,您调用str.split()
,这是str
类'方法 - 这需要首先使用字符串(str
对象的实例)才能工作。这就是你传递2个参数的原因。
所以回答,区别在于:
l = "sfrsfs"
str.split(l, '') # l is the string instance you'd like to split, '' the separator
但是,如果你这样称呼:
str.split("list, ''")
您在字符串split()
上调用"list, ''"
方法,split()
默认为默认分隔符。
另外,请注意str.split(my_string, '')
与my_string.split('')
相同。
答案 1 :(得分:0)
当你有这个代码时:
ten_things = "Apples Oranges Crows Telephone Light Sugar"
stuff = str.split(ten_things, ' ')
然后stuff
将['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn']
正如您所期望的那样。
但是当你跑步时:
ten_things = "Apples Oranges Crows Telephone Light Sugar"
stuff = str.split("ten_things, ' '")
那么你根本就没有使用ten_things
,你也可以只写第二行!
您只是按空格分割字符串"ten_things, ' '"
,最终stuff
为['ten_things,', "'", "'"]
。