Multiline F-String in Python
When Python 3.6 came in, it introduced a whole new segment to format strings, i.e., f-Strings
. It provides us a way to evaluate various Python expressions present inside a string and is also a faster and more efficient formatting method.
This tutorial will demonstrate string formatting with f-Strings
and multiline f-Strings
.
the f-Strings
in Python
f-Strings
, also known as formatting string literals, are always prefixed with an f
and have the substitute fields with curly braces. It is the fastest string formatting option since Python 3.6 because it is evaluated at run-time.
String formatting literals are used by starting the expressions with an f
. Then comes the type of string that can be a single quotation, a double quotation, or a triple quotation.
Finally, the Python expression is included inside the string, between the curly brackets.
Example:
name = "John"
print(f"How are you doing {name}?")
Output:
How are you doing John?
Multiline f-Strings
in Python
Multiline f-strings
are similar to using single line f-strings
in Python. It’s just that the string should be mentioned within the parenthesis, i.e., the curly braces.
Also, every line containing the f-string
should be started with an f
.
Example:
name = "John"
text = f"His name is {name}. " "He is a programmer. " f"{name} can code in Python. " f""
print(text)
Output:
His name is John. He is a programmer. John can code in Python.
Lakshay Kapoor is a final year B.Tech Computer Science student at Amity University Noida. He is familiar with programming languages and their real-world applications (Python/R/C++). Deeply interested in the area of Data Sciences and Machine Learning.
LinkedIn