The String format() method is a powerful method for formatting strings.
It allows you to create formatted strings by embedding variables and values into placeholders within a template string.
Syntax
template_str.format(value)format() Parameters
Python String format() method parameters:
| Parameter | Condition | Description |
|---|---|---|
value |
Required | one or more positional or keyword arguments |
However, another fundamental part is the template_str string, that contains format codes with placeholders for the arguments.
The general structure of a format specifier is {``field:fill``align``sign``#``width``group``.precision``type``}.
| Formatting options | Valid values |
|---|---|
field |
<any number or keyword to idenfity the argument to use> |
conversion |
s | r | a |
fill |
<any character> |
align |
< | > | = | ^ |
sign |
+ | – |
width |
<any number> |
group |
_ | , |
precision |
<any number> |
type |
b | c | d | e | E | f | F | g | G | n | o | s | x | X | % |
format() Return Value
Python String format() method returns a formatted string with the specified variables or values inserted into the placeholders within the template string.
Positional Arguments vs Keyword Arguments in String format()
Remember that format() method takes any number of arguments. But, they can be classified into two types of parameters:
Positional Arguments: list of parameters that can be accessed with index of parameter inside curly braces {index} (explicit positional index)
formatted_output = '{0} is {1} years old'.format('David', 25)
print(formatted_output) # Output: "David is 25 years old"Keyword parameters: list of parameters of type key=value, that can be accessed with key of parameter inside curly braces {key}
formatted_output = '{name} is {age} years old'.format(name='David', age=25)
print(formatted_output) # Output: "David is 25 years old"Examples
Example 1: Simple formatting with String format()
Comparison between default, positional and keyword arguments:
print("Hello {}, your age is {}.".format("David", 25))
print("Hello {0}, your age is {1}.".format("David", 25))
print("Hello {name}, your age is {age}.".format(name="David", age=25))output
Hello David, your age is 25.
Hello David, your age is 25.
Hello David, your age is 25.Example 2: Padding and Aligning Strings with String format()
You can:
- pad or create space around a value by increasing field size.
- force the field to be left, right or center-aligned within the available space.
The various alignment options are:
| Option | Meaning |
|---|---|
< |
Align Left |
> |
Align Right (default for numbers). |
= |
Add padding between sign & digits. (valid for numbers only) |
^ |
Align Center |
Some examples
left_aligned = '{:<12}'.format('Left')
right_aligned = '{:>12}'.format('Right')
center_aligned = '{:^12}'.format('Center')
print(left_aligned) # Output: 'Left '
print(right_aligned) # Output: ' Right'
print(center_aligned) # Output: ' Center 'output
Left
Right
Center Example 3: Truncate long strings with String format()
You can truncate long strings by using the .precision option.
For example take only the first three character of a string:
truncated = '{:.3}'.format('TutorialReference')
print(truncated) # Output: Tutoutput
TutOf course, you can combine it with other formatting settings, for example:
truncated = '{:#^12.3}'.format('TutorialReference')
print(truncated) # Output: ####Tut#####output
TutExample 4: Format integer numbers with String format()
Python provides various type codes to format integers:
| Type | Meaning |
|---|---|
b |
Binary format |
c |
Corresponding unicode character |
d |
Decimal Integer |
o |
Octal format |
x |
Hex format (lowercase letters) |
X |
Same as x, but uses uppercase letters |
n |
Number (Same as d, except it uses current locale setting for number separator) |
Some examples:
print("integer: {:d}".format(123)) # Output: integer: 123
print("float: {:f}".format(123.123456)) # Output: float: 123.123456
print("bin: {0:b}".format(12)) # Output: bin: 1100
print("oct: {0:o}".format(12)) # Output: oct: 14
print("hex: {0:x}".format(12)) # Output: hex: coutput
integer: 123
float: 123.123456
bin: 1100
oct: 14
hex: cExample 5: Format float numbers and decimals with String format()
For floating points, there are additional formatting options by specifying left justification, zero padding, numeric signs, total field width, and digits after the decimal point.
Following type codes are used to format floating points and decimal values.
| Type | Meaning |
|---|---|
e |
Exponential notation. (lowercase e) |
E |
Exponential notation (uppercase E) |
f |
Displays fixed point number (Default: 6) |
F |
Same as f. Except displays inf as INF and nan as NAN |
g |
General format. Rounds number to p significant digits. (Default precision: 6) |
G |
Same as g. Except switches to E if the number is large. |
% |
Percentage. Multiples by 100 and puts % at the end. |
For example, if you want to limit the number of digits after the decimal point, you can specify precision option.
result = '{:.2f}'.format(3.141592653)
print(result) # Output: 3.14output
3.14If you want to display numbers in scientific (exponential) notation, you use type code e or E (for uppercase letter)
result = '{:.2e}'.format(3141592653)
print(result) # 3.14e+09output
3.14e+09You can format numbers as percentages using the type code %. It multiplies the number by 100 and displays in floating-point f format, followed by a % percent sign.
result = '{:.2%}'.format(1/4)
print(result)output
25.00%Example 6: Format Signed Numbers with String format()
Negative numbers are prefixed with a sign by default. However, you can specify the sign format option for number types:
| Option | Meaning |
|---|---|
+ |
Displays sign for both positive and negative numbers |
– |
Displays sign only for negative numbers |
space |
Displays space for positive numbers and a minus sign for negative numbers |
For example, show sign for both positive and negative numbers:
result = '{:+.2f}, {:+.2f}'.format(1.23, -1.23)
print(result) # Output: +1.23, -1.23output
+1.23, -1.23For example, show sign only for negative numbers:
result = '{:+.2f}, {:+.2f}'.format(1.23, -1.23)
print(result) # Output: +1.23, -1.23output
+1.23, -1.23When you use ' ' (space) for sign option, it displays a leading space for positive numbers and a minus sign for negative numbers.
result = '{: .2f}, {: .2f}'.format(1.23, -1.23)
print(result) # Output: 1.23, -1.23output
1.23, -1.23Example 7: Padding Integers and Float numbers with String format()
In a similar way,you can pad a number by increasing field width.
For example, you can add a padding to a number
result = '{:5d}'.format(123)
print(result) # Output: ' 123'output
123For example, you can add leading zeros to a number by specifying 0 as fill character:
result = '{:0>5d}'.format(12)
print(result) # Output: '00012'output
00012For floating points, the padding value represents the length of the complete output (including decimal point and decimal digits). For example, let's padding zeros to a floating point:
result = '{:06.2f}'.format(12.3456789)
print(result) # Output: '012.35'output
012.35You can control the position of the sign relative to the padding using = alignment option.
For example, padding zeros to a negative number:
result = '{:0=8d}'.format(-123)
print(result) # Output: '-0000123'output
-0000123Example 8: Add Thousands Separator with String format()
The group format option ,, _ can be used as a thousand separator.
print('{:,}'.format(1234567890)) # Output: 1,234,567,890
print('{:_}'.format(1234567890)) # Output: 1_234_567_890output
1,234,567,890
1_234_567_890Example 9: Add Nibble Separator with String format()
For Hex, Octal and Binary numbers, _ underscore can be used to separate nibbles (nibble = 4 bits, i.e. 4 digits of a binary number).
print('{:_b}'.format(0b01010101010)) # Output: 10_1010_1010output
10_1010_1010Example 10: Datetime formatting with String format()
You can use the format() method to format a datetime object.
For example:
import datetime
my_date = datetime.datetime(2001, 5, 18, 12, 00, 00)
my_str = '{:%Y-%m-%d %H:%M:%S}'.format(my_date)
print(my_str) # Output: 2001-05-18 12:00:00output
2001-05-18 12:00:00Example 11: Parametrized formats in String format()
Python allows all of the format options to be specified dynamically using parametrization.
For example, let's parametrized fill, alignment and width:
result = '{:{fill}{align}{width}}'.format('center', fill='*', align='^', width='12')
print(result) # Output: ***center***output
***center***