String methods

The String objects also support a wide variety of operations implemented as methods. We can list those methods by using help() on the string type:

>>> help(str)

When you press Enter, you should see a display like this:

Help on class str in module builtins:

class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
:

On any platform you can browse through the help page by pressing the spacebar to advance one page at a time until you see the documentation for the capitalize() method, skipping over all the methods that begin and end with double underscores:

 |      Create and return a new object.  See help(type) for accurate    
| signature.

|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return self*value.
|
| __sizeof__(...)
| S.__sizeof__() -> size of S in memory, in bytes
|
| __str__(self, /)
| Return str(self).
|
| capitalize(...)
| S.capitalize() -> str
|
| Return a capitalized version of S, i.e. make the first
| character
have upper case and the rest lower case.
|
:

Press Q to quit the help browser, and we'll try to use captialize(). Let's make a string that deserves capitalization – the name of a capital city no less!

>>> c = "oslo"

To call methods on objects in Python we use the dot after the object name and before the method name. Methods are functions, so we must use the parentheses to indicate that the method should be called.

>>> c.capitalize()
'Oslo'

Remember that strings are immutable, so the capitalize() method didn't modify c in place. Rather, it returned a new string. We can verify this, by displaying c, which remains unchanged:

>>> c
'oslo'

You might like to spend a little time familiarizing yourself with the various useful methods provided by the string type by browsing the help.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset