How To Fancier Output Formatting in Python

Python provides a variety of ways to format output, including the use of placeholders, string concatenation, and string interpolation. In this blog post, we’ll take a closer look at some of the more advanced formatting options available in Python, with plenty of examples to illustrate each technique.

1. Format Specifiers

One of the most powerful and flexible formatting options in Python is the use of format specifiers. These are special codes that can be included within a string to control how the data is displayed. For example, the code "{:d}" is a format specifier that tells Python to format the following value as an integer. Here’s an example of how to use a format specifier:

# for digits 
age = 25
print("My age is {:d}".format(age))
# Output: My age is 25

You can also use format specifiers to control the number of decimal places to display, the alignment of the text, and many other formatting options. Here’s an example that uses several different format specifiers:

# for floats 
price = 9.99
print("The price is {:<10.2f}".format(price))
# Output: The price is 9.99     

In this example, {:<10.2f} tells Python to format the value as a floating point number with two decimal places and left-align it within a field of 10 characters.

2. f-strings

Another way to format output in Python is through the use of f-strings, F-strings, also known as formatted string literals, were introduced in Python 3.6 as a more concise and readable way to include expressions within a string that are evaluated at runtime. They are enclosed within curly braces {} and preceded by the letter f or F. Here’s an example of how to use an f-string:

name = "Alice"
age = 25
print(f"{name} is {age} years old.")
# Output: Alice is 25 years old.

As you can see, we can embed expressions directly inside a string by wrapping them in curly braces {}. The expressions are evaluated at runtime and replaced with their values. This can make the code more readable, especially when working with a lot of string concatenation.

Formatting with F-strings::

F-strings allow you to format the output using format specifiers similar to the ones used in the .format() method. For example, to format a number as a floating point with two decimal places, you can use the code f"{value:.2f}". Here’s an example:c

price = 9.99
print(f"The price is {price:.2f}")
# Output: The price is 9.99

You can also control the alignment of the text by using the <, >, ^ and = characters. For example, to left-align a value within a field of 10 characters, you can use the code f"{value:<10}". Here’s an example:

name = "Bob"
print(f"{name:<10}")
# Output: Bob     

F-strings also support nested expressions, allowing you to include the result of one expression inside another. Here’s an example:

x = 3
y = 5
print(f"The sum of {x} and {y} is {x + y}")
# Output: The sum of 3 and 5 is 8

3. Template Strings

Python also provides a way to use template strings, which are similar to f-strings but with slightly different syntax. A template string is created by enclosing a string in backticks (`) rather than single or double quotes. Here’s an example of how to use a template string:

from string import Template

name = "Alice"
age = 25
t = Template("$name is $age years old.")
print(t.substitute(name=name, age=age))
# Output: Alice is 25 years old.

In this blog post, we’ve looked at some of the more advanced formatting options available in Python, including format specifiers, f-strings, and template strings. Each of these techniques has its own strengths and weaknesses, and the best choice will depend on the specific requirements of your project. With practice and experimentation, you’ll be able to choose the best formatting option for your needs and create beautiful, easy-to-read output in Python.

Thanks for the read. Comment down for queries or for suggestions

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories