28 - String formatting

Using 'format' method:

Primarily String formatting can be done in python using the format method.

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

Using f-strings:

  • This is a new string formatting mechanism introduced by the PEP 498 under PEP 8.

  • 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.

  • Example:

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.
  • We can also use this in a single statement as well. To do some math:
print(f"{2 * 30})"  

# Output:
60

f-string Methods

  • Print literally the f-string
  • if we wanna give examples of f-strings inside it, we have to do like this:-
gender = male
age = 20

print("i am a {gender}, of {age} years old.") # this will print with gender and age values
print("i am a {{gender}}, of {{age}} years old.") # this will not print with values


#Output 
i am a male , of 20 years old.
i am {gender}, of {age} years old.