Formatted String in Python. Topic – 19

formatted string In python

In Python, string formatting can be accomplished using the format method.

Example:

Python
txt = "For only {price:.2f} dollars!"
print(txt.format(price=49))
Python

Here, we have formatted a string using the format method. The price variable is formatted inside {price:.2f}, which displays only two decimal places.

f-Strings in Python:

  • f-string is a new string formatting mechanism introduced through PEP 498. F-string are also known as Literal String Interpolation or more commonly F-strings.
  • The primary focus of this mechanism is to simplicity.

When we prefix the string with the letter ‘f’, the string becomes the f-string itself. f-string provides a convenient way to easily form a string and we also can calculate the value in the string.

Example:

Python
val = 'Geeks'  
print(f"{val} for {val} is a portal for {val}.")  
name = 'Priti'  
age = 23  
print(f"Hello, My name is {name} and I'm {age} years old.")
Python

The Output Of This Code Will Be:

Python
Hello, My name is Priti and I'm 23 years old.
Python

In this example, we use f-string for formatting the strings and we put the value dynamically. t evaluates at runtime; we can put all valid Python expressions in them.

Example

Python
print(f"{2 * 30}")
Python

The Output Of This Code Will Be:

Python
60
Python

If you don’t know the “Tuples & Its Operations in Python” just click on read more.

I hope you understand Formatted String in Python  Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog