F-strings are introduced in Python 3.6. They provide an efficient way to format strings.
F-strings make it easier for us to create easy-to-read and maintainable code.
F-strings are literal strings with the prefix 'f' or 'F'.
Usage of f-strings.
With Python f-strings, I can embed expressions inside string literals.
The syntax is simple. I need to prefix the string with the letter 'f' or 'F' and enclose any expressions
I want to include in curly braces {}.
Below is a simple example of how to use f-strings:
name = "Lance"
age = 35
print(f"My name is {name}, and I am {age} years old.")
In this example, I create a string with two variables, name and age.
By enclosing the variables in curly braces, I have created a template that will substitute the values of these variables at runtime.
The output is:
My name is Lance, and I am 35 years old.
Evaluate expressions in f-strings.
What I like the most about the f-strings is their ability to evaluate expressions.
That means I can include any valid Python expression inside curly braces, which will be evaluated and substituted with its result.
Here is another example:
Evaluate expressions in f-strings
a = 5
b = 3
print(f"The sum of {a} and {b} is {a + b}.")
Here I have used an expression inside the f-string to calculate the sum of variables a and b.
The resulting output is:
Format numbers and strings.
F-strings can also be used to format numbers and strings in various ways. Below are some examples.
Format numbers and strings
# Format a number with a certain number of decimal places
pi = 3.141592653589793
print(f"Pi is approximately equal to {pi:.2f}")
# Format an integer with leading zeros
num = 42
print(f"The answer is {num:03d}")
# Format a string with a fixed width and center it
word = "Python"
print(f"|{word:^10}|")
In the first example, I used an f-string to format the value of pi to two decimal places.
The expected output is:
Pi is approximately equal to 3.14
In the second example, I used an f-string to format the integer value of num with leading zeros.
The output is:
In the third example, I used an f-string to format the string value of a word with a fixed width of 10 characters.
Then I centered it.
The output is: | Python |
Create dynamic SQL queries.
F-strings can also be used in more advanced scenarios. For example, I can use f-strings to construct SQL queries
dynamically.
Here is how to do it:
Create dynamic SQL queries
table = "users"
column = "name"
name = "John"
query = f"SELECT * FROM {table} WHERE {column} = '{name}'"
print(query)
In the above example, I used an f-string to construct a SQL query that selects all records from a
table where a specific column matches a specific value. So I have three variables table, column, and column name.
By enclosing those variables in curly braces, I can create a template that can be filled in dynamically at runtime.