Python F-String Cool Features and Tips

Python F-String Cool Features and Tips

 

In Python, f-strings (formatted string literals) are a convenient and efficient way to embed expressions inside string literals. They are available in Python 3.6 and later versions. An f-string is prefixed with the letter f or F, and expressions inside curly braces {} are evaluated at runtime and formatted into the string.

 

How you can use f-string in python

1.Dynamic variable inside string

 

name: str = “shani kumar”
greeting: str = f"Hello {name}!")
print(greeting)

Output

Hello shani kumar!

 

2.Multiline string

name: str = “Shani Kumar”
age: int = 26
address: str = “Noida”
 
print(f"""
         Hi my name is {name}
         i am {age} old
         and i live in {address}
""")

Output

Hi my name is Shani Kumar
i am 26 old
and i live in Noida

 

3.Basic expression evaluation:

x: int = 10
y: int = 20 
result: str = f"The sum of {x} and {y} is {x + y}." 
print(result)

Output

The sum of 10 and 20 is 30.

 

4. Use variable name and its value

name: str = “Shani Kumar”
print(f"{name = }")  # python version >= 3.10

Output

name = Shani Kumar

 

5.Seprates the number 

num: int = 10000000
print(f"{num:_}")  # Seprate no by _
print(f"{num:,}") # seprate no by ,

Output

10_000_000
10,000,000

 

 6.Working with float number round up

num: float = 25.005
print(f"{num:.2f}")   # after . get two digit
print(f"{num:.3f}")   # after . get three digit

Output

25.00
25.005

 

7. String Padding

name: str = “Shani Kumar”
print(f"{name:50}")  # 50 whitespaces in right side
print(f"{name:<50}")  # same as above
 
print(f"{name:>50}") # 50  whitespaces in left side
 
print(f"{name:^50}") # variable value in center left and right side spaces

Output

Shani Kumar
                                       Shani Kumar
              Shani Kumar

 

8.Date formatting

from datetime import datetime
current_date = datetime.now() 
formatted_date = f"Today's date is {current_date:%B %d, %Y}" 
print(formatted_date)

Output

Today's date is November 13, 2024

 

Keep learning keep growing!

 

Related Posts
Essential Python Commands For Virtual Environment.
Essential Python Commands For Virtual Environment.

A virtual environment in Python is an isolated workspace that allows you to install and manage packa...

Python