f-strings are string literals that begin with a f or F and contain curly braces that contain expressions that will be replaced with their values. At runtime, the expressions are evaluated. This method is very helpful in string formatting.
In Python 3.6, f-strings (formatted string literals) were introduced. String interpolation is simple with these string methods. We are now going to explore the new f-string formatting technique. In comparison to earlier Python string formatting techniques, it has a simple syntax.
You can also checkout other python Strings tutorials:
- How To Convert Python String To Array
- How to Trim Python string
- Python String join Example
- Python Array of Strings
- How To Match String Item into List Python
- How To Convert String to int and int to string
- Python re match Example
- How To Use Regex With Python
How To Use f-string Method
Let’s take a simple example to format a string using f-string. The Strings in Python are usually enclosed within double quotes (""
) or single quotes (''
). To format a string using f-strings method, You only need to add an ‘f’ or an ‘F’ before the opening quotes of your string.
The simple string example: "This"
The f-string example: f"This"
Some examples of formatted string literals:
Format a string using a single variable:
name = "Adam" print(f"Hi, I am {name}.")
Let’s format a string using multiple variables:
name = "Adam" country = "United States" print(f"Hi, I am {name} and living {country}.")
Format string using nested fields:
width = 15 precision = 4 value = decimal.Decimal("18.34567") print(f"result: {value:{width}.{precision}}")
Example 2
You can insert a variable into the string and make it part. Let’s print the sum of two numbers in a single string using f-string:
x = 8 y = 5 #without f string word_string = x + ' plus ' + y + 'equals: ' + (x+y) word_string = f'{x} plus {y} equals: {x+y}'
Output:
8 plus 5 equals: 13