Understanding Python f-string
PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-String in Python is to make string interpolation simpler.
To create an f-string in Python, prefix the string with the letter “f”. The string itself can be formatted in much the same way that you would with str. format(). F-strings provide a concise and convenient way to embed Python expressions inside string literals for formatting.
String Formatting with F-Strings
In this code, the f-string f”My name is {name}.” is used to interpolate the value of the name variable into the string.
Python3
name = 'Ele' print (f "My name is {name}." ) |
My name is Ele.
This new formatting syntax is very powerful and easy. You can also insert arbitrary Python expressions and you can even do arithmetic operations in it.
Arithmetic operations using F-strings
In this code, the f-string f” He said his age is {2 * (a + b)}.” is used to interpolate the result of the expression 2 * (a + b) into the string.
Python3
a = 5 b = 10 print (f "He said his age is {2 * (a + b)}." ) |
He said his age is 30.
We can also use lambda expressions in f-string formatting.
Lambda Expressions using F-strings
In this code, an anonymous lambda function is defined using lambda x: x*2. This lambda function takes an argument x and returns its double.
Python3
print (f "He said his age is {(lambda x: x*2)(3)}" ) |
He said his age is 6
Float precision in the f-String Method
In this code, f-string formatting is used to interpolate the value of the num variable into the string.
Syntax: {value:{width}.{precision}}
Python3
num = 3.14159 print (f "The valueof pi is: {num:{1}.{5}}" ) |
The valueof pi is: 3.1416
Note: To know more about f-strings, refer to f-strings in Python
Python String Formatting – How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string.
You will learn different methods of string formatting with examples for better understanding. Let’s look at them now!