一つ、わからないことがあります...
text = "hello world" があり、それを分割したいとします。
いくつかの場所で、テキストを分割したい人が次のことをしているのを見ます:
string.split(text)
他の場所では、人々がただやっているのを見ます:
text.split()
違いは何ですか?なぜあなたはどちらかの方法で行うのですか?それについて理論的な説明をしてもらえますか?
興味深いことに、2 つの docstring は 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関数を検索する) ため、2 つの形式が完全に同等であることがわかります。
これstring.split(stringobj)
はstring
モジュールの機能であり、個別にインポートする必要があります。むかしむかし、これが文字列を分割する唯一の方法でした。それはあなたが見ている古いコードです。
は、モジュールよりも新しいstringobj.split()
文字列オブジェクト の機能です。しかし、それにもかかわらず、かなり古いです。それが現在の慣習です。stringobj
string
追記:str
S.Lottが上で指摘したように、文字列型です。つまり、次の2つの形式があります。
'a b c'.split()
str.split('a b c')
# both return ['a', 'b', 'c']
str.split
...は非バインドメソッドであり、はオブジェクトs.split
のバインドメソッドであるため、同等です。str
2番目のケースでは、渡される文字列がメソッドと同じようにstr.split
使用されself
ます。
これはここではあまり違いはありませんが、Pythonのオブジェクトシステムがどのように機能するかについての重要な機能です。
簡単な答え: string モジュールは、python 1.6 より前はこれらの操作を実行する唯一の方法でした。それ以来、メソッドとして文字列に追加されています。
好きな方を使用してください。ただし、str.split が推奨される方法であることに注意してください。:-)
string.split は、同じことを行う少し古い方法です。
str.split はもう少し効率的ですが (string モジュールをインポートしたり、そこから名前を検索したりする必要がないため)、string.split を好む場合は大きな違いを生み出すほどではありません。