gpt4 book ai didi

python - string.split(text) 或 text.split() : what's the difference?

转载 作者:太空狗 更新时间:2023-10-29 17:21:25 24 4
gpt4 key购买 nike

有一件事我不明白......

假设您有一个 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() (搜索 split 函数)。

关于python - string.split(text) 或 text.split() : what's the difference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/333706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com