String Replacement Fields in Python
Python String Replacement Fields
Like all other programming languages python also have a string modulo operator which is generally used to format string data. Python also offers some string replacement fields for ease of doing string formatting that’s why Python is one of the favorite programming languages.
The Python String .format() Method
Here we will learn string.format() method which is very useful to do formatting in string dynamically by replacing placeholder with values we provide.
Syntax
.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') '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') '007.ndls.indb/indbindb.ndlsndls.007007'
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') 'foo/bar/baz'
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') 'foo/bar/baz'
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment