Dir:
The dir() function returns the properties and methods available for an object.
For example, let’s say you have a variable defined whose value is a string as shown:
>> sample_string = "blog_example"
>>> sample_string
'blog_example'
>>> type(sample_string)
<class 'str'>
In the above example, a variable of type ‘string’ is defined.
To see the methods that can be used on that variable, using the dir() function, we have:
>> dir(sample_string)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>>
So, if we wanted to capitalise the values of that string, we know that we can use the ‘upper’ method shown as an option. We use it as follows:
>> sample_string.upper()
'BLOG_EXAMPLE'
>>>
This function is very useful for knowing what methods you can use on an object.
Another useful function is ‘help’. You can use the ‘help’ function to find out what a given method does. For example, if you type the following:
>> help(sample_string.upper)
You get the below output:
These two functions are helpful for better understanding what methods are available for a given object, and what the method does.