String Replacement Fields in Python


Python String Replacement Fields

Python is a way easier to write code as we compare it with other programming languages. Like all other languages python also have a string modulo operator which is generally used to format string data. But python also offers some string replacement fields for ease of doing string formatting that’s why Python is one of the favorite programming languages.

Here we will learn:

  • The string.format() method

The Python String .format() Method


<template>.format(<positional_argument(s)>, <keyword_argument(s)>)

Note that it is a technique, not an operator. The < template > method, which is a string containing the replacement fields, is called. The method specifies < positional arguments > and < keyword arguments > values that are inserted into < template > instead of the replacement fields. The resulting formatted string is the return value of the method.

Replacement fields are enclosed in curly braces ({}) in the < template > string.A literal text that is copied directly from the template to the output is anything not contained in curly braces. If you need to include, in the template string, a literal curly bracket character, such as {or}, then you can escape this character by doubling:

>>> '{{ {0} }}'.format('Hello')
'{ Hello }'

Now lets talk about arguments, there are two ways to pass the arguments in string.format() method:

1. Positional Arguments:

Positional arguments are inserted instead of numbered replacement fields into the template. Like list indexing, replacement field numbering is zero-based. The number of the first positional argument is 0, the number of the second is 1, and so on:

>>> '{0}/{1}/{2}'.format( 'indb',  'ndls',  '007')

Note that replacement fields don’t have to appear in numerical order in the template. In any order, they can be specified, and they can appear more than once:

>>>  '{2}.{1}.{0}/{0}{0}.{1}{1}.{2}{2}'.format('indb', 'ndls', '007')

The numbers in the substitute fields can be omitted, in which case the interpreter assumes a sequential order. This is known as automatic numbering of a field:

>>> '{}/{}/{}'.format('indb', 'ndls', '007')

2. Keyword Arguments:

Keyword arguments are inserted into the template string in place of keyword replacement fields with the same name:

>>> '{x}/{y}/{z}'.format(x='foo', y='bar', z='baz')