When Python programmers do the formatting of strings, they mostly use the format() method. But Python 3.6 and later introduces a new concept of string formatting. PEP 498 in Python came up with a new string formatting mechanism called Literal String Interpolation. In the developers' community and among programmers, it is commonly called the F-strings (where the leading 'f' represents the formatting). The main goal behind the introduction of f-strings is to make string interpolation simpler. In this tutorial, you will learn how to use f-strings in Python.
What are f-Strings in Python?
In general, strings in Python remain enclosed within double quotes ("Blabla") or single quotes ('Blabla'). But for creating f-strings, programmers need to add an 'f' or an 'F' (either small caps or large caps) before the opening quotes of the string. Such a string itself can be used to format in much the same way that programmers do using the str.format(). The moto behind F-strings is to render a concise and convenient method of embedding python expressions within a string literal for better formatting.
Example:
name1 = 'Gaurav'
name2 = 'Karlos'
a = 'author'
print(f"{name1} - {name2} is a name of the {a}.")
name = 'Sue'
clas = 12
print(f"Hello, My name is {name} and I read in class {clas}.")
Output:
Explanation:
First we have created a variable name1 and assign a string. But the special feature of f-string is it can execute simple expressions also within the curly braces (here 6 * 4). On the next print() statement we have again use the f-string but this time we are converting the string variable name1 to lowercase using lower() method, which is again possible within the curly braces.
How to Print Variables using Python f-Strings?
For printing a variable within f-Strings, programmers need to specify the names of the variable(s) within a set of curly braces {} in between wherever required. Now, when we will run the Python program containing the f-string, it will unfold the variables residing within the curly braces at runtime. All variable names will get replaced with their assigned values.
The syntax along with the curly braces of f-string will look something like:
f"This is an example of f-string where {var_name} and {var_names} are placed within curly braces."
Arbitrary Expressions within F-string:
As you know that f-strings gets evaluated at runtime, programmers can put any or all valid Python expressions within them. And the best part is they won't be treated as strings, rather they will be treated as constants and expressions. Such a facility allows programmers to perform some nifty things.
name1 = 'Gaurav'
print(f"{6 * 4}")
print(f"{name1.lower()} is funny.")
Output:
Explanation:
Here we have created a variable n with a string value. Then we have created another variable mail with another string value. Another integer value gets assigned with the age and finally a tuple inside which we are providing the f-string that can take variables and replace them with their respective values when the program gets executed. Here, we run the tuple using the userdata tuple within the print() function.
Multi-line Python’s f-string:
The f strings concept also supports multi-line string formatting. Programmers can create a multiline Python f string by enclosing the entire f string within a round parenthesis. Also, programmers can assign one or multiple f-strings under one variable name and display it separately.
Program:
n = "Gaurav Karlos"
mail = "karlos.ray007@xyz.com"
age = 28
userdata = (
f"Name: {n} \n"
f"Email: {mail} \n"
f"Age: {age} \n"
)
print(userdata)
Output:
Another program:
name = "Gaurav"
profession = "Developer"
affiliation = "Python certified"
disp = {
f"Hello {name}. "
f"You are a {profession}. "
f"You were in {affiliation}."
}
print(disp)
Output:
Here we have taken three strings name, profession, and affiliation. Then have taken another variable within which we are displaying the f-string one by one. Finally, we use disp within the print() to display it completely.
NOTE:
Programmers cannot use backslash in format string directly, something like this:
print(f"newline: {ord('\n')}")
or
a = 23
print(f"newline: Hi {a'\n'} Hello")
Otherwise, it will show an error message like this:
But this works:
newline = '\n'
print(f"Newline: {newline} Just above")
Output:
Comments and Printing Hashes using f-string:
While using an f string, programmers should not include a hashtag or pound (#) sign as it denotes a comment still you want to perform some work at runtime. This will look weird to the Python interpreter and will generate a syntax error. But if you want to print a pound sign to show something number count or numbering, use it outside the curly braces.
To leverage a hashtag in a string, make sure it gets formatted in the string part, instead of the curly braces.
Program:
rno = "G604"
print(f"Room number is: #{rno}")
Output:
Anything like this
rno = "G604"
print(f"Room number is: {#rno}")
will show an error.
Conclusion:
Python's f strings are a new and cooler tool that allows programmers to put expressions, constants, and variables within string literals without much hassle. Such an approach of formatting has numerous advantages compared to other ways of formatting. F strings are more straightforward to read and implement. Programmers can implement them well even when they are working with many different values.