有一件事我不明白…
假设您有一个text=“Hello World”,并且您想要拆分它。
在某些地方,我看到想要拆分文本的人正在执行以下操作:

string.split(text)

在其他地方,我看到人们只是在做:
text.split()

有什么区别?为什么你要用一种方式还是另一种方式?你能给我一个理论解释吗?

最佳答案

有趣的是,在python 2.5.1中,这两个文档字符串并不完全相同:

>>> import string
>>> help(string.split)
Help on function split in module string:

split(s, sep=None, maxsplit=-1)
    split(s [,sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string s, using sep as the
    delimiter string.  If maxsplit is given, splits at no more than
    maxsplit places (resulting in at most maxsplit+1 words).  If sep
    is not specified or is None, any whitespace string is a separator.

    (split and splitfields are synonymous)

>>> help("".split)
Help on built-in function split:

split(...)
    S.split([sep [,maxsplit]]) -> list of strings

    Return a list of the words in the string S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator.

深入了解,您会发现这两个表单完全等效,因为string.split(s)实际上调用了s.split()(搜索拆分函数)。

10-06 05:17
查看更多