Python Language String Formatting Basics of String Formatting

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

foo = 1
bar = 'bar'
baz = 3.14

You can use str.format to format output. Bracket pairs are replaced with arguments in the order in which the arguments are passed:

print('{}, {} and {}'.format(foo, bar, baz))
# Out: "1, bar and 3.14"

Indexes can also be specified inside the brackets. The numbers correspond to indexes of the arguments passed to the str.format function (0-based).

print('{0}, {1}, {2}, and {1}'.format(foo, bar, baz))
# Out: "1, bar, 3.14, and bar"
print('{0}, {1}, {2}, and {3}'.format(foo, bar, baz))
# Out: index out of range error

Named arguments can be also used:

print("X value is: {x_val}. Y value is: {y_val}.".format(x_val=2, y_val=3))
# Out: "X value is: 2. Y value is: 3."

Object attributes can be referenced when passed into str.format:

class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('My value is: {0.value}'.format(my_value))  # "0" is optional
# Out: "My value is: 6"

Dictionary keys can be used as well:

my_dict = {'key': 6, 'other_key': 7}
print("My other key is: {0[other_key]}".format(my_dict))  # "0" is optional
# Out: "My other key is: 7"

Same applies to list and tuple indices:

my_list = ['zero', 'one', 'two']
print("2nd element is: {0[2]}".format(my_list))  # "0" is optional
# Out: "2nd element is: two"

Note: In addition to str.format, Python also provides the modulo operator %--also known as the string formatting or interpolation operator (see PEP 3101)--for formatting strings. str.format is a successor of % and it offers greater flexibility, for instance by making it easier to carry out multiple substitutions.

In addition to argument indexes, you can also include a format specification inside the curly brackets. This is an expression that follows special rules and must be preceded by a colon (:). See the docs for a full description of format specification. An example of format specification is the alignment directive :~^20 (^ stands for center alignment, total width 20, fill with ~ character):

'{:~^20}'.format('centered')
# Out: '~~~~~~centered~~~~~~'

format allows behaviour not possible with %, for example repetition of arguments:

t = (12, 45, 22222, 103, 6)
print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*t)    
# Out: 12 22222 45 22222 103 22222 6 22222

As format is a function, it can be used as an argument in other functions:

number_list = [12,45,78]
print map('the number is {}'.format, number_list)
# Out: ['the number is 12', 'the number is 45', 'the number is 78']   
    

from datetime import datetime,timedelta
    
once_upon_a_time = datetime(2010, 7, 1, 12, 0, 0)
delta = timedelta(days=13, hours=8,  minutes=20)
    
gen = (once_upon_a_time + x * delta for x in xrange(5))
    
print '\n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen))
#Out: 2010-07-01 12:00:00
#     2010-07-14 20:20:00
#     2010-07-28 04:40:00
#     2010-08-10 13:00:00
#     2010-08-23 21:20:00


Got any Python Language Question?