String Format Python Example
To make sure a string will display as expected, we can format the result with the format()
 method.
The format()
 method allows you to format selected parts of a string.
Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input?
Basic formatting with format()
Example: Add a placeholder where you want to display the count:
1 2 3 4 |
msg="There are {} owls".format(5) print(msg) |
Output:
1 2 3 4 |
There are 5 owls >>> |
Example: In the following example, we format three strings.
1 2 3 4 |
msg="There are {} oranges, {} apples and {} bananas".format(10,5,25) print(msg) |
Output:
1 2 3 4 |
There are 10 oranges, 5 apples and 25 bananas >>> |
Example:
1 2 3 4 5 6 7 8 |
price =100 count =5 msg="Price:{} Count:{} Sum:{}".format(price,count,price*count) print(msg) |
Output:
String formatting by index numbers
Example:Â You can use index numbers (a number inside the curly brackets {0}
) to be sure the values are placed in the correct placeholders:
1 2 3 4 5 6 7 |
quantity = 3 itemno = 567 price = 49 myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." print(myorder.format(quantity, itemno, price)) |
Output:
1 2 3 4 |
I want 3 pieces of item number 567 for 49.00 dollars. >>> |
String formatting by Named Indexes
It is also possible to make use of variables inside the curly brackets, as shown in the example below. The variables are defined inside format(). Therefore, when it executes, the value assigned to the variable is replaced inside the original string.
Example:
1 2 3 4 |
msg="Welcome to {name} Site".format(name="Code4Example") print (msg) |
Output:
1 2 3 4 |
Welcome to Code4Example Site >>> |
Example:
1 2 3 4 |
myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Ford", model = "Mustang")) |
Output:
1 2 3 |
I have a Ford, it is a Mustang. |
Numbers formatting with format()
Example: Simple number formatting
1 2 3 4 5 6 7 8 9 10 |
# integer arguments print("The number is:{:d}".format(123)) # float arguments print("The float number is:{:f}".format(123.4567898)) # octal, binary and hexadecimal format print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12)) |
Output:
1 2 3 4 5 |
The number is: 123 The number is:123.456790 bin: 1100, oct: 14, hex: c |
Example: It will give the output in decimal format when used inside the placeholder
1 2 3 4 |
val ="The binary to decimal value is : {:d}".format(0b0011) print(val) |
Output:
1 2 3 4 |
The binary to decimal value is : 3 >>> |
Example :It will give the output in binary format when used inside the placeholder
1 2 3 4 |
val = "The binary value is : {:b}".format(500) print(val) |
1 2 3 4 |
The binary value is : 111110100 >>> |
Example : It will give the output in scientific format when used inside the placeholder, the exponent e in the output will be lowercase.
1 2 3 4 |
val = "The scientific value is : {:e}".format(40) print(val) |
Output:
1 2 3 4 |
The scientific value is : 4.000000e+01 >>> |
Example: It will give the output in scientific format when used inside the placeholder, the exponent E in the output will be uppercase
1 2 3 4 |
val = "The scientific value is : {:E}".format(40) print(val) |
Output:
1 2 3 4 |
The scientific value is : 4.000000E+01 >>> |
Example: This will output a fixed-point number format. By default, you will get the output of any number with six decimal places. In case you need up to 2 decimal places, use it as. 2f i.e.. a period (.) in front of 2f
1 2 3 4 |
val = "The value is : {:f}".format(40) print(val) |
Output:
1 2 3 4 |
The value is : 40.000000 >>> |
Example:Â
1 2 3 4 |
val = "The value is : {:.2f}".format(40) print(val) |
Output:
1 2 3 4 |
The value is : 40.00 >>> |
Example: This will output octal format
1 2 3 |
print("The value is : {:o}".format(500)) |
Output:
1 2 3 |
The value is : 764 |
Example: This will output hex format in lowercase
1 2 3 |
print("The value is : {:x}".format(500)) |
Output:
1 2 3 |
The value is : 1f4 |
Example: This will output hex format in uppercase.
1 2 3 |
print("The value is : {:X}".format(500)) |
Output:
1 2 3 |
The value is : 1F4 |
Example: This will output number format.
1 2 3 |
print("The value is : {:n}".format(500.00)) |
1 2 3 |
The value is : 500 |
Example: This will give the output in a percentage format. By default it will give 6 decimal places for the percentage output, in case you don’t want any decimal value you can use period with 0 i.e (:.0%).
1 2 3 4 |
print("The value is : {:%}".format(0.80)) print("The value is : {:.0%}".format(0.80)) |
Output:
1 2 3 4 5 |
The value is : 80.000000% The value is : 80% >>> |
Example: This will output an underscore as a thousand separator. It is available from python 3.6+.
1 2 3 |
print("The value is {:_}".format(1000000)) |
Output:
1 2 3 |
The value is : 1_000_000 |
Example: This will output comma as a thousands separator
1 2 3 |
print("The value is : {:,}".format(1000000)) |
Output:
1 2 3 |
The value is : 1,000,000 |
Example: This example shows how to add space or padding before the given number. The number 5 indicates the space count you want before the number.
1 2 3 |
print("The value is: {:5}".format(40)) |
1 2 3 |
The value is: 40 |
Example: The example shows how to get the output with a plus (+) sign before the number using {:+}.
1 2 3 |
print("The value is: {:+}".format(40)) |
1 2 3 |
The value is: +40 |
Example: The example shows how to get the output with a plus (+/-) sign before equal to sign using {:=}.
1 2 3 |
print("The value is {:=}".format(-40)) |
1 2 3 |
The value is -40 |
Example: The example shows to use {:^} to center align the text. The number 10 is used to add 10 spaces to show the center-aligned when the value is replaced.
1 2 3 |
print("The value {:^10} is positive value".format(40)) |
Output:
1 2 3 |
The value 40 is a positive value |
Example: The space of 10 is added using (:>10), and the value replaced is right-aligned.
1 2 3 |
print("The value {:>10} is positive value".format(40)) |
Output:
1 2 3 |
The value 40 is positive value |
Example : The space of 10 is added using (:<10), and the value replaces is left aligned.
1 2 3 |
print("The value {:<10} is positive value".format(40)) |
1 2 3 |
The value 40 is positive value |
Formatting class and dictionary members using format()
Example: Formatting class members using format()
1 2 3 4 5 6 7 8 9 |
# define Person class class Person: age = 23 name = "Adam" # format age print("{p.name}'s age is: {p.age}".format(p=Person())) |
Output:
1 2 3 |
Adam's age is: 23 |
Example : Formatting dictionary members using format()
1 2 3 4 5 6 7 |
# define Person dictionary person = {'age': 23, 'name': 'Adam'} # format age print("{p[name]}'s age is: {p[age]}".format(p=person)) |
Output:
1 2 3 |
Adam's age is: 23 |
Padding Variable Substitutions
Example: In below example will add space inside the Placeholder using the format(). To add space, you have to specify the number of spaces inside curly brackets after the colon(:). So the Placeholder will look like {:5}.
1 2 3 |
print("I have {:5} dogs and {:5} cat".format(2,1)) |
Output:
1 2 3 |
I have 2 dogs and 1 cat |
Example: You can also give the index inside the placeholder for example: {0:5} where 0 will refer to the first value inside format.
1 2 3 |
print("I have {0:5} dogs and {1:5} cat".format(2,1)) |
Output:
1 2 3 |
I have 2 dogs and 1 cat |
Example : Number formatting with padding for int and floats
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# integer numbers with minimum width print("{:5d}".format(12)) # width doesn't work for numbers longer than padding print("{:2d}".format(1234)) # padding for float numbers print("{:8.3f}".format(12.2346)) # integer numbers with minimum width filled with zeros print("{:05d}".format(12)) # padding for float numbers filled with zeros print("{:08.3f}".format(12.2346)) |
Output:
1 2 3 4 5 6 7 |
12 1234 12.235 00012 0012.235 |