String Formatting in Python

In python, string formatting can be done by using a string format() method. To format the strings, you need to add curly braces { } in the text so that the format() method will use those curly braces { } as placeholders to replace them with the required content.

 

Following is the syntax of format() method in python to format the strings.

 

string.format(arg1, arg2, etc.)

The python format() method will accept unlimited parameters and replace the curly brace { } placeholders with the content of the respective parameters.

 

Following is the example of formatting strings in python using format() method.

 

str1 = "Welcome to {}".format("Tutlane.com")
print(str1)
name = "Suresh"
age = 33
str2 = "My name is {}, and I am {} years old"
print(str2.format(name, age))

If you observe the above example, we created strings with single and multiple placeholders (curly brace { }) to replace with required parameter values using format() method.

 

When you execute the above python program, you will get the result as shown below.

 

Welcome to Tutlane.com
My name is Suresh, and I am 33 years old

String Format with Positional/Keyword Arguments

To make sure the arguments are replaced in the correct order, you can define the positional or keyword arguments in the placeholders like as shown below.

 

# Positional arguments
str1 = "{1} to {0}".format("Tutlane.com", "Welcome")
print(str1)
# Keyword arguments
name = "Suresh"
age = 33
str2 = "My name is {x}, and I am {y} years old"
print(str2.format(y = age, x = name))

If you observe the above example, we defined the placeholders with positional and keyword arguments to specify the order.

 

When you execute the above python program, you will get the result as shown below.

 

Welcome to Tutlane.com
My name is Suresh, and I am 33 years old

In python, you can also format the placeholder's text by using different formatting types like <, >, ^, etc., based on your requirements.

 

Following is the example of formatting the placeholder’s text by using different format types in python.

 

msg6 = "The site has {:_} views"
print(msg6.format(3000000))
msg6 = "Site started with {:d} views"
print(msg6.format(3000))
msg7 = "The number is {:e}"
print(msg7.format(50000))

If you observe the above example, we used different format types inside of placeholders { } to format the placeholder's text based on requirements.

 

When you execute the above python program, you will get the result as shown below.

 

The site has 3_000_000 views
Site started with 3000 views
The number is 5.000000e+04

To know more about formatting types in placeholders, refer python string format() method.

 

This is how you can perform string formatting in python using the format() method with different formatting types based on your requirements.