Day-28 f-strings

String formatting in python
String formatting can be done in python using the format method.
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
f-strings in python
It is a new string formatting mechanism introduced by the PEP 498. It is also known as Literal String Interpolation or more commonly as F-strings (f character preceding the string literal). The primary focus of this mechanism is to make the interpolation easier.
When we prefix the string with the letter 'f', the string becomes the f-string itself. The f-string can be formatted in much same as the str.format() method. The f-string offers a convenient way to embed Python expression inside string literals for formatting.
Example
val = 'Geeks'
print(f"{val}for{val} is a portal for {val}.")
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")
Output:
Hello, My name is Tushar and I'm 23 years old.
In the above code, we have used the f-string to format the string. It evaluates at runtime; we can put all valid Python expressions in them.
We can use it in a single statement as well.
Example
print(f"{2 * 30})"
Output:
60
Practice
letter = "Hey my name is {1} and I am from {0}"
country = "India"
name = "Harry"
print(letter.format(country, name))
print(f"Hey my name is {name} and I am from {country}")
print(f"We use f-strings like this: Hey my name is {{name}} and I am from {{country}}")
price = 49.09999
txt = f"For only {price:.2f} dollars!"
print(txt)
# print(txt.format())
print(type(f"{2 * 30}"))
Output:
Hey my name is Harry and I am from India
Hey my name is Harry and I am from India
We use f-strings like this: Hey my name is {name} and I am from {country}
For only 49.10 dollars!
<class 'str'>
Explanation:
letter.format(country, name){0}→country→"India"{1}→name→"Harry"Output:
Hey my name is Harry and I am from India
f"Hey my name is {name} and I am from {country}"- Direct variable interpolation using f-strings.
Double braces
{{and}}- Used to print literal
{and}characters.
- Used to print literal
{price:.2f}Formats the float to 2 decimal places.
49.09999becomes49.10.
f"{2 * 30}"Evaluates the expression
2 * 30→60.An f-string always returns a string,




