有一件事我不明白...
想象一下,你有一个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函数)。
这string.split(stringobj)
是string
模块的一个特性,必须单独导入。曾几何时,这是拆分字符串的唯一方法。那是您正在查看的一些旧代码。
是字符串对象的stringobj.split()
一个特征stringobj
,它比string
模块更新。不过还是挺老的。这就是目前的做法。
额外说明:str
是字符串类型,正如 S.Lott 上面指出的那样。这意味着这两种形式:
'a b c'.split()
str.split('a b c')
# both return ['a', 'b', 'c']
...是等价的,因为str.split
是未绑定的方法,而是对象s.split
的绑定方法str
。在第二种情况下,传入的字符串与方法str.split
中一样使用self
。
这在这里没有太大区别,但它是 Python 对象系统如何工作的一个重要特征。
简短的回答:字符串模块是在 python 1.6 之前执行这些操作的唯一方法——它们已经作为方法添加到字符串中。
使用任何你喜欢的方法,但要意识到 str.split 是推荐的方法。:-)
string.split 是做同样事情的老方法。
str.split 效率更高一些(因为您不必导入字符串模块或从中查找任何名称),但如果您更喜欢 string.split,则不足以产生巨大的差异。