Python: Format String

By Xah Lee. Date: . Last updated: .

The format a string, you can use the optional args with print [see Python: Print String]. Or, use the more general string method format.

Note, there is no sprintf.

‹string›.format()

str.format(arg1, arg2, etc).

Inside the string, use {spec} as placeholder. spec is specification for the format, can be empty.

print("{} cats {} dogs.".format(3,4))
# 3 cats 4 dogs.

Use double braces {{}} to include literal brace pair {}

# use {{}} to include literal {}
print("braces {{}}".format() == "braces {}")

Format Codes

# {:s} is for string
print("{:s}".format("cat") == "cat")

# integer
print("{:d}".format(3) == "3")

# binary
print("{:b}".format(3) == "11")

# hexadecimal
print("{:x}".format(10) == "a")

# list
print("{:}".format([7, 8]) == "[7, 8]")

Format number in human readable format:

print("{:,}".format(123456789) == "123,456,789")

Change Print Argument Order

print("{1:}, {0:}".format(3, 4) == "4, 3")

Thanks to Yuri Khan for a suggetion on Python print.

Python String