Python: String Format Method
format Method
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 Format Argument Order
print("{1:}, {0:}".format(3, 4) == "4, 3")
2012-03-25 Thanks to Yuri Khan for a suggetion on Python print.