Python: The .format (String 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 curly bracketss {{}}
to include literal curly brackets pair {}
# use {{}} to include literal {} print("curly brackets {{}}".format()) # curly brackets {}
Format Codes
String
# {:s} is for string print("{:s}".format("cat")) # cat
Integer
# integer print("{:d}".format(3)) # 3
to Binary
# to binary print("{:b}".format(3)) # 11
to Hexadecimal
# to hexadecimal print("{:x}".format(10)) # a
List
# list print("{:}".format([7, 8])) # [7, 8]
Add number separator
print("{:,}".format(123456789) == "123,456,789") # True
Change Format Argument Order
print("{1:}, {0:}".format(3, 4) == "4, 3") # True