Earlier we have learned many functions provided by strings, including split(), join(), find(), index(), etc., but this is far from all its methods. Due to the limited space, this chapter can only give you some of the most used functions. As for other functions, the reader can check them by using the dir() and help() functions introduced in this section.
The Python dir() function is used to list the entire contents of a class or a module, including variables, methods, functions, and classes. Its usage is:
dir(obj)
obj represents the object to be viewed. obj can be left unwritten, at which point dir () lists the variables, methods, and defined types in the current scope.
The Python help() function is used to view the help documentation of a function or module. Its usage is:
help(obj)
obj represents the object to be viewed. obj can be left unwritten, and help() will enter the help subroutine.
After mastering the above two functions, we can review the usage and functions of all methods, functions, variables, and classes in Python.
[Example] Use dir() to view all methods supported by the string type (str):
dir(str)
The output is:
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',]
[Example] Use help () to see the usage of upper() function in str type:
help(str.upper)
The output is:
Help on method_descriptor:
upper(self, /)
Return a copy of the string converted to uppercase.
As you can see, the upper() function is used to convert the letters in the string to uppercase and return a new string.
Note that when using help() to view the usage of a function, the function name cannot be enclosed in parentheses. For example, it is wrong to write the above command as help (str.upper ()).
help(str.upper())
The output is:
---------------------------------------------------------------------------
TypeError raceback (most recent call last)
[ipython-input-5-f8bc63c28e1a] in [module]
----> 1 help(str.upper())
TypeError: descriptor 'upper' of 'str' object needs an argument
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises