f-strings
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-strings is to make string interpolation simpler.
To create an f-string, 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.
Example: Formatting Strings using f-strings
Python3
n1 = 'Hello' n2 = 'w3wiki' # f tells Python to restore the value of two # string variable name and program inside braces {} print (f "{n1}! This is {n2}" ) |
Hello! This is w3wiki (2 * 3)-10 = -4
We can also use f-strings to calculate some arithmetic operations and it will perform the inline arithmetic. See the below example –
Example: Inline arithmetic using f-strings
Python3
a = 2 b = 3 c = 10 print (f "({a} * {b})-{c} = {(2 * 3)-10}" ) |
(2 * 3)-10 = -4
Note: To know more about f-strings, refer to f-strings in Python
Python String InterpolationPython String Interpolation
String Interpolation is the process of substituting values of variables into placeholders in a string. Let’s consider an example to understand it better, suppose you want to change the value of the string every time you print the string like you want to print “hello <name> welcome to geeks for geeks” where the <name> is the placeholder for the name of the user. Instead of creating a new string every time, string interpolation in Python can help you to change the placeholder with the name of the user dynamically.
Contact Us