Python String Formatting Methods

There are several methods for string formatting in Python.

  1. I must be fully aware of the rules.
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old" % (name, age)
print(formatted_string)
  1. Using the method str.format()
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old".format(name, age)
print(formatted_string)
  1. Format using f-strings, for example:
name = "Charlie"
age = 20
formatted_string = f"My name is {name} and I am {age} years old"
print(formatted_string)
  1. rearrange()
name = "David"
age = 35
formatted_string = "My name is {0} and I am {1} years old".format(name, age)
print(formatted_string)
  1. rearrange()
name = "Eve"
age = 40
formatted_string = "My name is {name} and I am {age} years old".format(name=name, age=age)
print(formatted_string)
bannerAds