Practical Examples and Use Cases
The print()
function with format specifiers can be used in a variety of practical scenarios. Here are a few examples:
Suppose you have a list of stock prices and you want to display them in a nicely formatted way:
stock_prices = [120.45, 98.76, 135.23, 87.54]
for price in stock_prices:
print("The stock price is $%.2f" % price)
Output:
The stock price is $120.45
The stock price is $98.76
The stock price is $135.23
The stock price is $87.54
In this example, we use the %.2f
format specifier to limit the number of decimal places displayed for each stock price.
You can also use format specifiers to customize the display of string data:
name = "LabEx"
age = 5
print("My name is %s and I am %d years old." % (name, age))
Output:
My name is LabEx and I am 5 years old.
Here, we use the %s
format specifier to insert the name
variable and the %d
format specifier to insert the age
variable.
The print()
function can also be used to format datetime objects:
import datetime
current_date = datetime.datetime.now()
print("The current date and time is %s." % current_date)
print("The current date and time is %Y-%m-%d %H:%M:%S." % current_date)
Output:
The current date and time is 2023-04-17 12:34:56.789012.
The current date and time is 2023-04-17 12:34:56.
In this example, we use the %s
format specifier to display the full datetime object, and the %Y-%m-%d %H:%M:%S
format specifier to display the datetime in a specific format.
These are just a few examples of how you can use the print()
function with format specifiers to customize the output of your Python programs. The possibilities are endless, and the format specifiers can be combined and nested to achieve the desired output.