简体   繁体   中英

Q on Python Documentation: in "string.split(s)", why s in ( )?

I have recently started learning Python, and I'm having some hard time understand Python Documentation (www.python.org) on string module.

When I searched string module using Python Documentation (www.python.org), I get a list of string module functions that are taking an string variable ("s") in the parenthesis followed by the function name. For example, in the case of "string.split(s[, sep[, maxsplit]])", shouldn't it be "s.split([sep[, maxsplit]])"?

What I don't follow is that the string variable is in the parenthesis like an input variable.

If s = "I am splitting this sentence.", and I like to split the the sentence (string variable s) by spaces, the command should be s.split(). For example:

s = "I am splitting this sentence."

s.split()

['I', 'am', 'splitting', 'this', 'sentence.']

But, when I read the documentation, it sounds like I need to write the command as "split(s)" instead of "s.split()" because the string variable (s) is inside the parenthesis?

Can someone please explain why the string varible is inside the parenthesis ("string.split(s[, sep[, maxsplit]])")? Why isn't documentation not written as "s.split([sep[, maxsplit]])"?

[Added] Someone below mentioned that my question has been asked and answered on here, but I was not able to find the one. And, the question that I was pointed to is not the same question as mine at all... Please help!

There is a "string" module, which implements many of the same functions as the string object "str". Both are valid. You can do string.split('foo bar baz') or 'foo bar baz'.split() .

"The string module contains a number of useful constants and classes, as well as some deprecated legacy functions that are also available as methods on strings."

It is the way method calls work in Python. Here is example:

class Test(object):
 def method(self):
  print 5

Now I can call it two ways:

t = Test()
t.method()

or:

t = Test()
Test.method(t)

So self is just first parameter. But first way is strongly preferred.

s is a string object. Strings have the method split(), and you access it using dot notation iessplit(). The bracket takes arguments, such as one for selecting what character to split by eg

"h.e.l*l.o.".split('*')

will return ['hel','l.o'], because asterisk has been specified as the argument for splitting the string. When you are talking about having s in the brackets in split (split(s)), s represents an argument. When the s is here: s .split, the s is a string object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM