Strings | String Formatting Method Calls

The string object’s format method uses the subject string as a template, and takes any number of arguments that represent values to be substituted according to the template. Curly braces designate substitution targets and arguments to be inserted either by position , or keyword, or relative position.

Formatting by position

>>> template = '{0} is {1} and {2}'
>>> template.format('Python', 'easy', 'awsome')
'Python is easy and awsome'

Formatting by keyword

>>> template = '{language} is {adj1} and {adj2}'
>>> template.format(language = 'Python', adj1 = 'easy', adj2 = 'awsome')
'Python is easy and awsome'

Formatting by relative position

>>> template = '{} is {} and {}'
>>> template.format('Python', 'easy', 'awsome')
'Python is easy and awsome'

The split() and replace() with formatting strings

>>> x = '{}, {}, or {}'.format(1, 2, [3, 4])
>>> x
'1, 2, or [3, 4]'
>>> 
>>> x.split(' or ')
['1, 2,', '[3, 4]']
>>> 
>>> y = x.replace('or', 'and')
>>> y
'1, 2, and [3, 4]'

Leave a Reply