Python - Clean way to format string

By xngo on June 25, 2019

In Python, formatting string using concatenation(+) can be messy. Luckily, string.format() make it easier and cleaner for you to format string. This method will parse your string and replace the placeholder({}) that you put in with the parameters that you pass to it. Here is a simple example.

"My name is {} {}".format("Joe", "Smith") # Output: My name is Joe Smith

Placeholder & parameter order

The placeholders({}) and the parameters don't have to follow the same order. You can specify a specific order for the placeholders and parameters. Here are some examples.

# Re-arranging the order of display without changing the arguments.
"{1} {0}".format("zero", "one") # Output: one zero
 
# Use named placeholders: first and last.
"My name is {first} {last}".format(last="Smith", first="Joe") # Output: My name is Joe Smith

Left or right alignment

# Allocate 5 character spaces for Joe & 7 for Smith.
"{:5s}|{:7s}|".format("Joe", "Smith") # Output: Joe  |Smith  |
 
# By default, left alignment is assumed. For right alignment, add >
"{:>5s}|{:>7s}|".format("Joe", "Smith") # Output:   Joe|  Smith|

Format numbers

# Padding number with zeros.
"{:06}".format(3) # Output: 000003
 
# Format pi up to 2 decimal points.
pi=3.14159
"{:.2f}".format(pi) # Output: 3.14

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.