10 Coolest Python Features — Part II
This is the continuation of the previous article where we saw 5 coolest features of Python. Please do read it here if you haven’t read it. In this article, we will be seeing another 5 coolest features of Python
6. Dictionary Comprehension
Dictionary Comprehension is similar to List Comprehension. Here we use dictionaries instead of lists.
Consider we want to generate the squares of N numbers in the form of a dictionary, where the key is the number and the value is its square.
Python offers a simple and attractive string formatting syntax called F-String. We can easily format and print a string with dynamic values using F-string.
Decorators are used for modifying the behavior of a function or class without changing its code. It can be considered as a wrapper function on top of another function or class. It is inspired by the Decorator Design Pattern.
Consider we want to print the execution time of all the functions that are called in a program. We can easily achieve the above functionality using decorators.
The zfill method can be used pad 0’s to the left of a string to make a string of a specific length.
Consider we need to print the current date in the format dd-mm-yyyy. We can use Python’s datetime module to get the current date, month, and year.
But if the month or date has a single digit, there won’t be a leading zero. zfill can be used to add a leading zero if the date or month is a single digit.
10. Any and All
Python offers two beautiful methods any and all which can be used to find if any or all the conditions are true respectively. Simply put, any behaves like a series of OR conditions and all behaves like a series of AND conditions.
Thank you 🤘
To know more about me, visit ganeshkumarm.me