If you are a Python programmer, you probably know how important it is to format strings properly, a skill that becomes particularly useful when you’re looking for help with Python assignment. Whether you want to print out a message, display some data, or create a report, you need to use string formatting to make your output look nice and readable.
But how do you format strings in Python?
There are several ways to format strings in Python, including the %
operator, str.format()
method, and template strings. But none are as simple and elegant as f-strings
.
F-strings are a new feature that was introduced in Python 3.6 that allows you to embed expressions inside string literals.
They are also called formatted string literals because they automatically format the expressions according to the specified format specifiers.
F-strings have many advantages over other methods of string formatting, such as:
They are faster because they are evaluated at runtime and not parsed by a separate method.
They are more readable because they use less syntax and avoid the need for placeholders or indices.
They are more expressive because they can use any valid Python expression inside them, including variables, functions, operators, and even other f-strings.
In this blog post, I will show you some of the tricks and tips that you can use with f-strings
to make your string formatting easier and more powerful. I will cover topics such as debugging, multiline strings, nested formatting, conditional formatting, string concatenation, and alignment and padding.
👉 Also learn:
From Dates to Holidays: Demystifying the "calendar" Module in Python
Debugging
One of the most common uses of f-strings
is to print out the values of variables or expressions for debugging purposes.
For example, if you want to check the value of a variable called x
, you can simply write:
x = 42
print(f"x = {x}")
This will print out x = 42
on the screen.
You can also use f-strings
to print out the values of complex expressions or function calls without having to assign them to variables first. For example:
import math
print(f"The area of a circle with radius 5 is {math.pi * 5 ** 2}")
This will print out The area of a circle with radius 5 is 78.53981633974483
.
But what if you want to print out both the name and the value of an expression?
For example, if you want to print out x = 42
, you have to write x
twice, once inside the f-string
and once outside. This can be tedious and error-prone.
Fortunately, there is a shortcut that you can use with f-strings
to automatically print out the name and the value of an expression.
You just have to use the =
operator inside an f-string
, like this:
x = 42
print(f"{x=}")
This will print out x=42
on the screen.
The
=
operator tells Python to print out both the name and the value of the expression that follows it.
You can use this trick with any expression, not just variables. For example:
import math
print(f"{math.pi * 5 ** 2=}")
This will print out math.pi * 5 ** 2=78.53981633974483
.
This trick is very useful for debugging your code quickly and easily.
You don’t have to worry about typing the name of the expression twice or using placeholders or indices. You just have to use one simple operator inside an f-string
.
💡 Speed up your blog creation with DifferAI.
Available for free exclusively on the free and open blogging platform, Differ.
Try DifferAI — Your Free Writing Assistant
Multiline Strings
Another useful feature of f-strings is that they can create multiline strings without having to use triple quotes or escape characters. However, unlike regular strings, f-strings
cannot span multiple lines by simply writing them across multiple lines. For example, if you try to write something like this:
s = f"This is a
multiline string"
print(s)
You will get a syntax error because Python expects the f-string
to end on the same line as it starts. To create a multiline string using f-strings
, you need to use one of the following methods:
- Using triple quotes
- Using parentheses
- Using backslashes
Using Triple Quotes
The easiest way to create a multiline string using f-strings
is to use triple quotes. Triple quotes are a set of three single (')
or double (")
quotation marks that allow you to create a string that spans multiple lines.
For example, you can create a multiline string using triple-double quotes like this:
s = f"""This is a
multiline string"""
print(s)
This will print out:
This is a
multiline string
The string starts and ends with three double quotes, which tells Python that it’s a multiline string. The text between the quotes can span as many lines as needed, and any line breaks or white space will be preserved in the resulting string.
You can also use triple single quotes to create a multiline string like this as well:
s = f'''This is another
multiline string'''
print(s)
This will print out:
This is another
multiline string
Note: In this case, there is no difference between using single or double quotation marks — you can use either one to create a multiline string.
One of the main advantages of using triple quotes to create a multiline string is that they are easy to read and maintain.
You can see exactly how the string is formatted and organized, without needing to use escape characters or other tricks to continue the string on multiple lines.
However, one limitation of this method is that it can be difficult to use triple quotes within the string itself since this can cause conflicts with the opening and closing quotes.
In such cases, you might need to use another method, such as parentheses or backslashes, to create your multiline string.
Using Parentheses
Another way to create a multiline string using f-strings
is to use parentheses to enclose an f-string
that spans multiple lines. This will tell Python to ignore the indentation spaces and only include the newline characters in the final string.
For example, if you want to create a SQL query that spans multiple lines, you may want to write something like this:
query = (f"SELECT name, age FROM users\n"
f"WHERE age > 18\n"
f"ORDER BY name")
print(query)
This will print out:
SELECT name, age FROM users
WHERE age > 18
ORDER BY name
Notice that there are no extra spaces at the beginning of each line. The parentheses tell Python to treat the f-string
as a single expression that spans multiple lines. The \n
characters tell Python to insert newline characters in the final string.
Using parentheses, you can create multiline strings with f-strings
without having to use triple quotes or escape characters. This can make your code more readable and concise.
Using Backslashes
A third way to create a multiline string using f-strings
is to use backslashes to continue an f-string
on the next line without adding a newline character. This will tell Python to ignore the newline characters in the code and join the f-strings
into one single line.
For example, if you want to create a SQL query that spans one line, you may want to write something like this:
query = f"SELECT name, age FROM users "\
f"WHERE age > 18 "\
f"ORDER BY name"
print(query)
This will print out:
SELECT name, age FROM users WHERE age > 18 ORDER BY name
Notice that there are no newline characters in the final string. The backslashes tell Python to ignore the newline characters in the code and join the f-strings into one single line.
Using backslashes, you can create multiline strings with f-strings without having to use triple quotes or escape characters. This can make your code more compact and efficient.
Nested Formatting
One of the most powerful features of f-strings is that they can nest inside each other to create more complex formatting.
For example, if you want to create a table with aligned columns using f-strings, you can write something like this:
data = [("Kuldeep", 23, "Engineer"),
("Bob", 30, "Doctor"),
("Charlie", 35, "Teacher")]
# Find the maximum lengths of each column
max_name = max(len(row[0]) for row in data)
max_age = max(len(str(row[1])) for row in data)
max_job = max(len(row[2]) for row in data)
# Create a dynamic format string for each column based on the maximum lengths
name_format = f"{{:>{max_name}}}"
age_format = f"{{:>{max_age}}}"
job_format = f"{{:>{max_job}}}"
# Print the table header
print(name_format.format("Name"), age_format.format("Age"), job_format.format("Job"))
# Print the table rows
for name, age, job in data:
print(name_format.format(name), age_format.format(age), job_format.format(job))
This will print out:
Name Age Job
Kuldeep 23 Engineer
Bob 30 Doctor
Charlie 35 Teacher
To create a dynamic format string for each column based on the maximum lengths of the data. We use curly braces inside an f-string
to embed another f-string
that specifies the alignment and padding for each column. We then use this format string to format each cell in the table.
Using nested f-strings
, you can create more complex formatting that depends on the values of other expressions. This can make your code more flexible and expressive.
Conditional Formatting
Another useful feature of f-strings
is that they can use conditional expressions inside them to create conditional formatting.
For example, if you want to print out a message based on the value of a variable called x
, you can write something like this:
x = 26
print(f"x is {x} and it is {'even' if x % 2 == 0 else 'odd'}")
This will print out x is 26 and it is even
.
The conditional expression inside an f-string
prints either even
or odd
depending on whether x
is divisible by 2 or not.
A conditional expression is a short way of writing an if-else statement in one line. It has the following syntax:
value_if_true if condition else value_if_false
You can use any valid Python expression as the condition or the values. You can also use conditional expressions to compare two variables and print out different messages based on their values. For example:
x = 42
y = 26
print(f"x is {x} and y is {y} and they are {'equal' if x == y else 'not equal'}")
This will print out x is 42 and y is 26 and they are not equal
.
Using conditional expressions inside f-strings
, you can create conditional formatting that depends on the values of other expressions. This can make your code more concise and elegant.
String Concatenation
Another feature of f-strings
is that they can concatenate strings without using the +
operator or the join()
method.
For example, if you want to join two strings with a comma, you can write something like this:
name = "Kuldeep"
age = 23
print(f"My name is {name}, and I am {age} years old.")
This will print out My name is Kuldeep, and I am 23 years old.
The f-string
automatically inserts the values of the expressions inside the curly braces into the final string.
You can also use
f-strings
to join strings with different separators, such as commas, spaces, or newlines.
For example, if you want to create a list of items using f-strings
, you can write something like this:
items = ["apple", "banana", "orange"]
print(f"The items are: {', '.join(items)}.")
This will print out The items are: apple, banana, orange.
We use the join()
method inside an f-string
to join the items with a comma and a space as the separator. The f-string
then adds a period at the end of the string.
You can also use f-strings
to create sentences, paragraphs, or any other text that requires string concatenation.
For example, if you want to create a paragraph using f-strings, you can write something like this:
name = "Kuldeep"
age = 23
job = "Engineer"
hobby = "reading"
print(f"{name} is {age} years old and works as an {job}. "
f"He likes {hobby} in his free time.")
This will print out:
Kuldeep is 23 years old and works as an Engineer. He likes reading in his free time.
We use two f-strings
to create a paragraph that spans two lines. The first f-string
ends with a space to avoid adding a newline character. The second f-string
starts with a space to avoid adding an extra space.
Using f-strings
, you can concatenate strings without using the +
operator or the join()
method. This can make your code more concise and elegant.
Alignment and Padding
Another handy feature of f-strings
is that they can align strings to the left, right, or center within a given width.
For example, if you want to align a string to the right within 10 characters, you can write something like this:
name = "Kuldeep"
print(f"{name:>10}")
This will print out Kuldeep
.
We use the >
operator inside an f-string
to specify that the string should be aligned to the right within 10 characters. The f-string then adds spaces to the left of the string to fill the width.
You can also use the <
operator to align a string to the left within a given width. For example:
name = "Kuldeep"
print(f"{name:<10}")
This will print out Kuldeep
.
You can also use the ^
operator to align a string to the center within a given width. For example:
name = "Kuldeep"
print(f"{name:^10}")
This will print out Kuldeep
.
The
^
operator inside an f-string specifies that the string should be aligned to the center within 10 characters. The f-string then adds spaces to both sides of the string to fill the width.
You can also use f-strings to pad strings with spaces or other characters to fill up the width. For example, if you want to pad a string with zeros instead of spaces, you can write something like this:
number = 42
print(f"{number:0>5}")
This will print out 00042
.
The 0
character before the >
operator inside an f-string to specifies that the string should be padded with zeros instead of spaces. The f-string then adds zeros to the left of the string to fill up the width.
You can also use any other character as the padding character. For example, if you want to pad a string with asterisks instead of spaces, you can write something like this:
name = "Kuldeep"
print(f"{name:*^10}")
This will print out *Kuldeep**
.
The *
character before the ^
operator inside an f-string specifies that the string should be padded with asterisks instead of spaces. The f-string then adds asterisks to both sides of the string to fill up the width.
Using f-strings
, you can align and pad strings to create formatted output, such as menus, headers, or tables. This can make your output more attractive and readable.
Thanks for reading!
More about f-strings from the docs.