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.
Table of Contents
There are two types of parameters for the Python 3 String format:
Related Page: Code Introspection in Python
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.
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
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
Here are some common operations performed on the python string template.
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.
As the name suggests, it contains the strings of the digits.
For example: ‘0123456789’.
It contains the strings of the hexadecimal digits.
For example: ‘0123456789abcdefgABCDEFG’
The string of the eight digits.
Example: ‘01234567’
Related Page: Python String Functions
These are following methods for the public methods:
We can perform string formatting in the Python format string. The Formatter class of the string module can be used to do string formatting.
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 ‘}}’.
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
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:
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!
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
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 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.
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 Chennai, Python Course Bangalore, Python Course Dallas, Python 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.
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:
Name | Dates | |
---|---|---|
Python Training | Dec 24 to Jan 08 | View Details |
Python Training | Dec 28 to Jan 12 | View Details |
Python Training | Dec 31 to Jan 15 | View Details |
Python Training | Jan 04 to Jan 19 | View Details |
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.