String Formatting - Python

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.

If you would like to become a Python certified professional, then visit Mindmajix - A Global online training platform:  Python Certification Course.  This course will help you to achieve excellence in this domain.

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

Code:

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.

Code:

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

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.

Output:

HeyUser, your account has been credited  1142.724

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)
print(String)

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.

Output:

HeyUser, your account has been credited  1142.724

MindMajix YouTube Channel

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’

Related Page: Python String Functions

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.

Code:

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

Output:

z, x, y

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

Code:

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

Output:

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:

Code:

name = 'User'
example = 'Hello, %s' % name
print(example)

Output:

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)
print(Example)
Output:

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:

Code:

name = 'Customer'
Example = 'Hello, {}'.format(name)
print(Example)

Output:

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.

Code:

name = 'User'
example =  f'Hello, {name}!'
print(example)

Output:

Hello, User!

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

Code:

x = 2
y = 5
example = f'Two plus five is {x + y} and not {2 * (x + y)}.'
print(example)

Output:

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.

Code:

from string import Template
t = Template('k means $k')
print (t.substitute({'k' : 1}))

Output:

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.

If you are interested to learn Python and to become an Python Expert? Then check out our Python Certification Training Course at your near Cities.

Python Course ChennaiPython Course BangalorePython Course DallasPython Course Newyork

These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Python and help you to achieve your dream job.

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

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Python TrainingNov 19 to Dec 04View Details
Python TrainingNov 23 to Dec 08View Details
Python TrainingNov 26 to Dec 11View Details
Python TrainingNov 30 to Dec 15View Details
Last updated: 03 Apr 2023
About Author

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.

read less
  1. Share:
Python Articles