Introduction to Python format() Function
Python has acquired a wide and peak level in the market like no language has done ever before, especially in the domain of Artificial Intelligence and Data Science. Knowing its methods helps python developers and python users work really smarter with it. Let’s discuss one very important python-format() function. To define a specific value in a particular format, the format() function is used.
Syntax:
format(value,format)
Here value refers to one, which needs to be represented. And python-format() function represents the form in which value has to be presented.
Examples of Python format() Function
Let’s see Python format() Function through some examples:
Example #1
Code:
x = format(0.08, '%')
print(x)
Output:
Code:
x = format(255, 'b')
print(x)
Output:
Here format ‘b’ represents binary form, and hence 255 after formatting shows “11111111”. The same can be formatted in hex, octal, decimal, etc.
Code:
x = format(255, 'o')
print(x)
Output:
Example #2
Formatting usually uses % and {} to represent values. % is associated with the data type, whereas {} is a placeholder irrespective of the data type. Let’s see it through an example:
Code:
emp_name = 'Leo Shein'
emp_age = 24
print("Name: %s Age:%d"%(emp_name,emp_age))
Output:
Code:
emp_name = 'Leo Shein'
emp_age = 24
print("Name: %s Age:%d"%(emp_name,emp_name))
Output:
As one can see, Name is associated with string and Age is associated with int. When we tried printing Age, which is associated with int with emp_name, it showed a format error. As one knows: %s represents string, %d represents int,%f represents float. While printing, if the format doesn’t match, TypeError is bound to come.
Example #3
Code:
emp_name = 'Leo Shein'
emp_age = 24
print("Name: {} Age: {}".format(emp_name,emp_age))
Output:
Code:
emp_name = 'Leo Shein'
emp_age = 24
print("Name: {} Age:{}".format(emp_name,emp_name))
Output:
As shown above, Age can also be printed with emp_name. As {} is just a placeholder, and one can associate any data type while formatting and printing a statement. The above placeholder can better be understood if the index is also kept inside empty {}. This is called a positional argument.
Example #4
Code:
emp_name = 'Leo Shein'
emp_age = 24
print("Name: {0} Age: {1}".format(emp_name,emp_age))
Output:
Here the index of “emp_name” is 0, an index of “emp_age” is 1. Hence the same has also been referenced while printing. However, if index 0 is replicated for “Age” as well, then see what happens.
Code:
emp_name = 'Leo Shein'
emp_age = 24
print("Name: {0} Age: {0}".format(emp_name,emp_age))
Output:
Because index 0 refers to ‘Leo Shein’, the same will come for “Age” as well.
Example #5
Here let’s see the example of mixed arguments in format function:
Code:
print("Hello {0}, your balance is {abc}.".format("Fina", abc=230.2346))
Output:
As one can see, we have used positional as well as keyword arguments. {0} refers to the name “Fina”. {abc} refers to value abc = 230.2346.
Example #6
Formatting with padding. Padding refers to the concept of adding spaces either to the right or left of the text/numeral.
Code:
print("{:6d}".format(12))
Output:
Here in order to print “12”, it’s been padded with 6d. That means 4 spaces, and then the digit gets displayed(as shown above). As alignment has not been specified, it’s aligned to the right by default. However, if you want to show spaces with zero, you can do that by placing 0 in front of the format specifier.
Code:
print("{:06d}".format(12))
Output:
Example #7
format() for signed numbers:
Code:
print("{:+f} {:+f}".format(21.99, -22.99)) # This will show the + sign
print("{:-f} {:-f}".format(21.99, -22.99)) # This will show the - sign only
Output:
Example #8
format() for string formatting
Code:
print("{:6}".format("dog")) # string-padding with left-alignment
print("{:>6}".format("dog")) # string-padding with right-alignment
print("{:^7}".format("dog")) # string-padding with center-alignment
Output:
As one notices here:
- Case 1: {:6} occupied 6 spaces, and the dog will be printed from the left. The remaining 3spaces will be just occupied.
- Case 2: {:>6} occupied 6 spaces, but the dog is printed at last. Front 3 places will remain blank.
- Case3: {:^7} occupies 7 spaces, and the dog will be printed with center alignment.
Example #9
Format Class members
Code:
class Employee:
id = 41
name = "Prince"
print("{p.name}'s company ID is: {p.id}".format(p=Employee())) # format name and id
Output:
As one notices, {p.name} and {p.id} is placeholder for values associated with class members in class “Employee”. The format() function helps you access the respective values of class members of a class.
Example #10
Truncate String using the format()
Code:
print("{:.5}".format("Singapore"))
print("{:^7.3}".format("Singapore"))# truncating strings to 3 letters, and then padding & center-aligned
Output:
- Case 1: Here {:.5} will truncate a string to the first five characters. Hence “Singapore” will come down to “Singa”.
- Case 2: Its combination of truncation and alignment. First, “Singapore” will be truncated to 3 characters, i.e. “Sin”, and then ^7 will help you center align “Sin” with the occupation of 7 spaces.
Conclusion
As we have seen above, how to format function and formatting operators play an important role in formatting the variables to a specific type in Python. There are ample of approaches available to format variables; one should be aware of the cases, which suits were, as per scenario.
Recommended Articles
This is a guide to Python format() Function. Here we discuss the Introduction to Python format() Function along with different examples and code implementation. You may also look at the following articles to learn more –
40 Online Courses | 13 Hands-on Projects | 215+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses