String Formatting - Python

  • (4.0)
  • | 948 Ratings |
  • Last Updated February 11, 2019

Python string format()

String formatting in Python allows us to do a number of substitutions in strings. Positional formatting can be used to concatenate a number of elements in a Python string. Concatenation of the elements can be done either with single or multiple strings.

The syntax of the format functions is: { }.format(value). The value here can be an integer, variable, strings, or characters.

Here is an example for understanding string format() of Python format string in a better way.


str = "I want to learn programming in {}"
print (str.format("Python"))

Here, we will be integrating another string in the string “I want to learn programming in”. The word “Python” will be inserted at the end of the string.

String Format() Parameters

There are two types of parameters for the Python 3 String format:

  • Positional Parameters: This is the list of parameters that can be accessed. The index of the parameter has to be provided in the curly braces.
  • Keyword Parameters: These are the parameters whose value is required to be entered. The value will be assigned according to the key of the parameter provided in the curly braces.

[Related Page: Code Introspection in Python]

How string format works?

The format() function simply reads the arguments provided in the parameters and then reformats the string according to them. However, the formatting varies as per the positional or keyword arguments.

Positional Arguments:

The argument lists in Python begin from the 0. In the example given below, argument 0 is defined as a string ‘User’ whereas the argument 1 is a floating number 1142.7238. As you can see in the string that for argument 1, we have provided an operation (9.3f) of Python format float which would be required to be performed on the floating number.


String = "Hey{0}, your account has been credited {1:9.3f}".format("User", 1142.7238)

Here, “User” was argument ‘0’ and “1142.7238” was argument ‘1’. As we are only specifying the position of the keyword and arguments, it is called the positional argument.


HeyUser, your account has been credited  1142.724

Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo!

Keyword Arguments:

Instead of using the index for specifying the position of the arguments, we will simply use keywords and assign the values to them.

String = "Hey{Name}, your account has been credited {Credits:9.3f}".format(Name = "User",Credits =  1142.7238)

As you can see, we are not specifying the index anymore, but we are specifying the Keywords for some values. This method is helpful when we have to deal with a large number of values whose indexes are difficult to remember.


HeyUser, your account has been credited  1142.724

String- common string operations

Here are some common operations performed on the python string template.

String Constants

  • string.ascii_letters:

The concatenation of ASCII characters is possible by specifying the required case, which can be either uppercase or the lowercase. Since there is no need for any specification, that is, locale specification in this case, hence this constant is not locale dependent.

Example: the string ‘abcdefg’ is lowercase and the string ‘ABCDEFG’ is uppercase.

  • string.digits:

As the name suggests, it contains the strings of the digits.
For example: ‘0123456789’.

  • string.hexdigits:

It contains the strings of the hexadecimal digits.
For example: ‘0123456789abcdefgABCDEFG’

  • string.octdigits:

The string of the eight digits.
Example: ‘01234567’

These are following methods for the public methods:

  • format: This is the primary API method in Python and inserts the values in the string using the positional and keyword arguments.
  • vformat: It is used in the case if we want to include the predefined library of the arguments rather than inserting the user-defined arguments in the string.
  • parse: This method loops over the string and then it returns an iterable of tuples. The vformat method uses this to break the string into the literal text or the field.
  • check_unused_args:This function checks for any unused arguments or keyword arguments which were meant to be used with the function, however they are not used by the format().
  • Convert_field: This converts the value of the conversion type as per the specified conversion types.

String Formatting

We can perform string formatting in the Python format string. The Formatter class of the string module can be used to do string formatting.

Checkout Python Tutorials

Format String Syntax

The syntax of the formatter class and str.format() method is same for the format strings. However, in the case of the formatter class, one can define the syntax of the sub-classes.

The replacement fields of the format strings are defined by the braces ‘{}’.

Note: If you want to insert braces in your literal text, then you can do that by using the double braces ‘{{‘ and ‘}}’.

Format Examples

Here, we will be seeing the examples of new format syntax and the old ‘%’ formatting index. The general syntax is new format and is similar to the old one. Here, curly braces ‘{}’ and colon ‘:’ is used in spite of the ‘%’.
For example ‘%9.3f’ will be changed to the ‘{:9.3f}’.
The new format syntax allows us to use different functions such as, Accessing the arguments by using the position, and here is an example to demonstrate this.


example = '{0}, {2}, {1}'.format('z', 'y', 'x')


z, x, y

It is also possible to access the arguments using the names or keywords:


Example =  'Plane: {x}, {y}'.format(x='4', y='5')


Plane: 4, 5

Template Strings

With the ‘Template Strings’, it is possible to replace the ‘%’-based substitutions along with the ‘$’-based substitutions. Here are some rules that are required to be followed:

  • $$’ is identified as the escape and it is replaced with a single ‘$’.
  • $identifier’ is defined as the substitution placeholder. The placeholder contains the matching key of the “identifier”.
  • identifier” can be case sensitive ASCII alphanumeric character along with the underscores.
  • identifier” can begin with either underscore or any ASCII alphanumeric character.
  • The placeholder specification is terminated along with the first non-identifier character after the ‘$’ sign.
  • The ‘string’ module provides ‘template’ class which implements these rules.

“Old Style” String Formatting (% operator)

We can access the built-in operations of the ‘strings’ in Python string template with the use of the ‘%’ operator. It is also possible to do the conversions using the ‘%’ operator.

Here is an example:


name = 'User'
example = 'Hello, %s' % name


Hello, User

The ‘%’ string operator changes a little when we have to make number of substitutions. The ‘%’ operator only processes one argument, so it becomes necessary to turn the set of arguments in the form of tuple.

Here is an example:

name = 'User'
errno = 'Err5'
Example = 'Hey %s, there is a %s error!' % (name, errno)

Hey User, there is a Err5 error!

“New Style” String Formatting (str.format)

A new way of string formatting was introduced in Python 3. One does not have to use the ‘%’ operator in this type of formatting. ‘format()’ function can be used to do simple positional formatting.

Here is an example:


name = &#39;Customer&#39;
Example = &#39;Hello, {}&#39;.format(name)


Hello, Customer

String Interpolation / f-Strings (Python 3.6+)

Python 3.6 provided a new programming format of formatting the strings. These are called formatted string literals or “f-strings”. With this method, embedded Python expressions can be used inside constants.


name = &#39;User&#39;
example =  f&#39;Hello, {name}!&#39;


Hello, User!

With this method, one can embed arbitrary Python expressions along with the inline arithmetic, and here is an example:


x = 2
y = 5
example = f&#39;Two plus five is {x + y} and not {2 * (x + y)}.&#39;


Two plus five is 7 and not 14.

Frequently Asked Python Interview Questions & Answers

Template Strings (Standard Library)

Template strings are also one of the tools available for string formatting in Python. Here is an example to understand it better.


from string import Template
t = Template(&#39;k means $k&#39;)
print (t.substitute({&#39;k&#39; : 1}))


k means 1

As you have seen, we should import the ‘template’ from the ‘string’ module.

Which String Formatting Method Should You Use?

Since, with a number of ways available for string formatting, it depends upon the needs of the user. If the format strings are supplied by the user for the web applications, and as it can cause the security issues, then one should go for ‘Template Strings’.

In case if there are no such security issues, then the user should use ‘String Interpolation / f-Strings’ if the user has Python 3.6+, otherwise (“New style” str.format) can be used.

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings. Protection Status