Python has various methods for string formating to control over the appearance of the displayed data on the screen. This previous tutorial has explained the string formatting using modulo ‘%’ character.
This tutorial has illustrated the second method for string formatting using Python’s built-in string str.format()function. The string on which this method is called can contain text or replacement fields delimited by braces {}
.
Each replacement field contains either the numeric index of a positional argument or the name of a keyword argument. The str.format() function return a copy of a string where each replacement field is replaced with the string value of the corresponding argument.
In [1]: x = "Hello, {} {}! How are you?".format("Mark","Ronsn") print(x) Out[1]: Hello, Mark Ronsn! How are you?
You can also add the index of a positional argument in the replacement field.
In [2]: print("Hello, {1} {0}! How are you?".format("Mark","Ronsn")) Out[2]: Hello, Ronsn Mark! How are you?
You can also pass the name of the keyword argument in the replacement field.
In [3]: print("Hello, {fname} {lname}! How are you?".format(fname = "Mark",lname="Ronsn")) Out[3]: Hello, Mark Ronsn! How are you?
You can also use the Python dictionary to pass the argument in the replacement field.
In [4]: name = {"fname":"Mark","lname":"Ronsn"} print("Hello, {fname} {lname}! How are you?".format(**name)) Out[4]: Hello, Mark Ronsn! How are you?
You can also use the sequence as an argument and unpack it.
In [5]: print("{} + {} = {}".format(*'123')) Out[5]: 1 + 2 = 3
In [6]: print("{2} + {0} = {1}".format(*'143')) Out[6]: 3 + 1 = 4
. . .
Text Alignment & specifying a width
Option | Meaning |
---|---|
'<' |
Forces the field to be left-aligned within the available space. |
'>' |
Forces the field to be right-aligned within the available space. |
'=' |
Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types. It becomes the default when ‘0’ immediately precedes the field width. |
'^' |
Forces the field to be centered within the available space. |
In most of the cases, the syntax is similar to the modulo %
-formatting, with the addition of the {}
and with :
used instead of %
. For example, '%03.2f'
can be translated to '{:03.2f}'
.
Examples
In [7]: print("{:<30}".format("Hello, Python")) # width: 30 & '<': 'left aligned' print("{:>30}".format("Hello, Python")) # width: 30 & '>': 'right aligned' print("{:^30}".format("Hello, Python")) # width: 30 & '^': 'center aligned' print("{:*<30}".format("Hello, Python")) # width: 30 & '<': 'left aligned' & '*' as a fill char print("{:@^30}".format("Hello, Python")) # width: 30 & '^': 'center aligned' & '@' as a fill char Out[7]: 'Hello, Python ' ' Hello, Python' ' Hello, Python ' 'Hello, Python*****************' '@@@@@@@@Hello, Python@@@@@@@@@'
. . .
The Sign Option
The sign option is only valid for number types.
Option | Meaning |
---|---|
'+' |
indicates that a sign should be used for both positive as well as negative numbers. |
'-' |
indicates that a sign should be used only for negative numbers (this is the default behavior). |
space | indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers. |
In [8]: print('{:f}; {:f}'.format(1.23, -1.23)) # Defalult: No sign Out[8]: 1.230000; -1.230000 In [9]: print('{:+f}; {:+f}'.format(1.23, -1.23)) # Use '+' sign Out[9]: +1.230000; -1.230000 In [10]: print('{:-f}; {:-f}'.format(1.23, -1.23)) # USe '-' sign Out[10]: 1.230000; -1.230000 In [11]: print('{: f}; {: f}'.format(1.23, -1.23)) # Use ' '(space) sign Out[11]: 1.230000; -1.230000
. . .
Type Conversation
Type | Meaning |
---|---|
'b' |
Binary format. Outputs the number in base 2. |
'c' |
Character. Converts the integer to the corresponding Unicode character before printing. |
'd' |
Decimal Integer. Outputs the number in base 10. |
'o' |
Octal format. Outputs the number in base 8. |
'x' |
Hex format. Outputs the number in base 16, using lower-case letters for the digits above 9. |
'X' |
Hex format. Outputs the number in base 16, using upper-case letters for the digits above 9. |
'n' |
Number. This is the same as 'd' , except that it uses the current locale setting to insert the appropriate number separator characters. |
'e' |
Exponent notation. Prints the number in scientific notation using the letter ‘e’ to indicate the exponent. The default precision is 6 . |
'E' |
Exponent notation. Same as 'e' except it uses an upper case ‘E’ as the separator character. |
'f' |
Fixed-point notation. Displays the number as a fixed-point number. The default precision is 6 . |
'F' |
Fixed-point notation. Same as 'f' , but converts nan to NAN and inf to INF . |
In [12]: print("int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(125)) Out[12]: int: 125; hex: 7d; oct: 175; bin: 1111101
. . .
The '#'
Option – This option is only valid for integer, float, complex and Decimal types. '#'
option adds the prefix '0b'
, '0o'
, or '0x'
to the output value binary, octal and hexadecimal respectively.
In [13]: print("int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(125)) Out[13]: int: 125; hex: 0x7d; oct: 0o175; bin: 0b1111101
The ','
Option – Use the comma as a thousands separator
In [14]: print('{:,}'.format(1525008750)) Out[14]: 1,525,008,750
The ‘%’ percentage Character – Multiplies the number by 100 and displays in fixed ('f'
) format, followed by a percent sign.
In [15]: print('Percentage: {:.1%}'.format(12/52)) # 12/15 = 0.23076 Out[15]: Percentage: 23.1%
. . .