Python - Getting help / Discover functions available

By xngo on June 27, 2019

In Python, the built-in function dir() will list all the available attributes of an object. The informations returned are quite useful as it also returns a list of functions available for that object. Let me show you an example.

str = "OpenWritings.net"
print(dir(str))

It will show you the followings:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

Everything that are listed without underscore are functions that you can use on str. Do you recognize the common functions that you can perform on a string: lower(), upper(), capitalize(), etc? As you can see, dir() is quite helpful to let you know what are the available functions.

Here are examples using the functions listed.

str = "OpenWritings.net"
 
print(str.lower())
print(str.upper())
print(str.capitalize())

Output

openwritings.net
OPENWRITINGS.NET
Openwritings.net

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.