Python - String Formatting Method Basics

Introduction

Within the subject string, curly braces designate substitution targets and arguments to be inserted either by position (e.g., {1}), or keyword (e.g., {food}), or relative position.

For example:

Demo

template = '{0}, {1} and {2}'                             # By position 
print( template.format('test', 'ham', 'eggs') ) 

template = '{motto}, {pork} and {food}'                   # By keyword 
print( template.format(motto='test', pork='ham', food='eggs') )

template = '{motto}, {0} and {food}'                      # By both 
print( template.format('ham', motto='test', food='eggs') )

template = '{}, {} and {}'                                # By relative position 
print( template.format('test', 'ham', 'eggs') )

Result

How the two techniques compare:

Demo

template = '%s, %s and %s'                                # Same via expression 
print( template % ('test', 'ham', 'eggs') )

template = '%(motto)s, %(pork)s and %(food)s' 
print( template % dict(motto='test', pork='ham', food='eggs') )
print( '{motto}, {0} and {food}'.format(42, motto=3.14, food=[1, 2]) )

Result

format method creates and returns a new string object.

Related Topic