Member-only story
Python 101 — f Strings
Understanding and Utilizing f-Strings in Python
When it comes to formatting strings in Python, the conventional method involves using the format() method.
However, starting from Python 3.6, there's a more elegant and succinct alternative – f-Strings. Officially known as formatted string literals, f-Strings offer a streamlined syntax and prove to be incredibly useful for string formatting tasks.
What are f-Strings?
In Python, strings are typically enclosed within double quotes (“ ”) or single quotes (‘ ’).
To create f-Strings, you simply add an f or F before the opening quotes of your string. For instance, while “This” is a regular string, f”This” becomes an f-String.
Printing Variables with f-Strings
Using f-Strings to display variables is straightforward. Place the names of the variables within curly braces { }.
At runtime, the variables' names will be replaced with their actual values. If there are multiple variables, enclose each name within curly braces.
name = "Elise"
country = "France"
print(f"I'm {name} and I am from {country}.")
# Output: I'm Elise and I am from France.