- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Formatting containers using format() in Python
When using Python, container style can be a useful means of enhancing the readability and maintainability of code. You can style lists, tuples, dictionaries, sets, and even classes quickly and simply using this method. You can adjust how your data is presented by aligning columns, adding padding, and setting accuracy by using the built-in format() method. In this article, we'll take a deep dive into container formatting using format() in Python, including various types of containers and how to use them with the format() function.
Container Formatting with format()
Assuming we have a list of numbers that we want to organize by separating each number with a comma and a space.
Example
my_list = [1, 2, 3, 4, 5] formatted_list = ', '.join(['{}'.format(x) for x in my_list]) print(formatted_list)
Output
1, 2, 3, 4, 5
The collection of formatted numbers with a comma and space separator is joined using the join() method in this case. Each integer value in the enumeration will substitute the " placeholder inside the format() method.
Although immutable, tuples are comparable to lists in that their contents cannot be altered once they have been formed. In this case, we joined the formatted tuple components with a comma and space using the join() method once more
Example
my_tuple = ('apple', 'banana', 'orange') formatted_tuple = ', '.join(['{}'.format(x) for x in my_tuple]) print(formatted_tuple)
Output
apple, banana, orange
By combining dictionary values and the format() method, dictionaries can be formatted.
Example
my_dict = {'name': 'ABCJohn', 'age': 33, 'city': 'Los Angeles'} formatted_dict = 'Name: {name}, Age: {age}, City: {city}'.format(**my_dict) print(formatted_dict)
Output
Name: ABCJohn, Age: 33, City: Los Angeles
In this case, we used format() method placeholders that matched the values in our dictionary. The dictionary is unpacked using the **my dict syntax, and its contents are then passed as keyword parameters to the format() method. Similarly, sets can be written inside of a set comprehension by using the join() and format() functions.
Example
my_set = {1, 2, 3, 4, 5} formatted_set = ', '.join(['{}'.format(x) for x in my_set]) print(formatted_set)
Output
1, 2, 3, 4, 5
Same can be done for Classes
Example
class Person: def __init__(self, name, age): self.name = name self.age = age my_person = Person('John', 30) formatted_person = 'Name: {p.name}, Age: {p.age}'.format(p=my_person) print(formatted_person)
Output
Name: John, Age: 30
Passing an instance of our class as a keyword argument to the format() function is a viable solution
Customization Options
In addition to formatting containers, the format() function also provides options to customize how the data is displayed. Some common options include padding, alignment, and precision.
To right-align a text within a specified breadth, for instance, we can use the '>' option. Think about a collection of characters we have −
my_list = ['apple', 'banana', 'orange']
We can format this list so that each string is right-aligned in a field of width 10 using the following code −
Example
my_list = ['apple', 'banana', 'orange'] for fruit in my_list: print('{:>10}'.format(fruit))
Output
apple banana orange
The < option and the ^ option can be used to centre and left-align the lines within the box, respectively. The precision selection, which enables us to choose how many numbers are presented after the decimal point, is another helpful choice. Consider a collection of floating-point values as an illustration −
my_floats = [1.23456, 2.34567, 3.45678]
We can format these numbers to display only two digits after the decimal point using the following code −
Example
my_floats = [1.23456, 2.34567, 3.45678] for num in my_floats: print('{:.2f}'.format(num))
Output
1.23 2.35 3.46
Additionally, we can use f-strings and other text editing methods in conjunction with format(). This enables us to design output lines that are more intricate and flexible. Let's look at a full code block that exemplifies container formatting in Python now that we know how to style containers with format().
Example
my_dict = {'apple': 1.23, 'banana': 2.34, 'orange': 3.45} for key, value in my_dict.items(): print('{:<10}{:.2f}'.format(key, value))
Output
apple 1.23 banana 2.34 orange 3.45
By using this code block, a dictionary is created that links the titles of three fruits to their corresponding values. The for loop loops through the dictionary's entries iteratively, formatting each key-value combination so that the value is shown with two digits after the decimal point and the key is left-aligned in a field with a width of 10. Container editing with format() has many applications in real-world settings. For instance, we might employ it to style tables or diagrams during data analysis. It may be used in web programming to present material in a user-friendly manner. We might use it in automation to produce records or files.
Conclusion
In summation, container formatting with Python's format() function is a strong instrument that enables us to present data in a flexible and comprehensible manner. We can produce content that is specific to our requirements by using the format() function with a range of container kinds and formatting choices. I trust that this piece has helped you comprehend container formatting in Python, and I invite you to learn more about it on your own.