In this post, we learn How To Use String Formatting In Python. Before we get started, if you want to data type in the python program, please go through the following article: Data Types In Python.

In Python string is a sequence of characters wrapped in single or double quotation marks. Python comes with an in-built method of String class for string formatting. Python str.format() method allows us to do string formatting and substitution operations. Let’s have a real-world example when you need string formatting.

Imagine you have a website which has many users these users are further divided into staff and regular users, Staff users have authority to access some private pages which regular user don’t. So when a regular user “Jhon” hits those URL’s we need to show  a message to our user like,

We have to use string formatting to print Username along with the Error because it is not possible to hardcode the error for every user.

How to do String Formatting in Python?

In Python string formatting works by putting placeholders which are nothing but a pair of curly braces{} in a string object, which are replaced by the arguments of the str.format() method, this can be better understood by the following example,

Here we created a  string object with a placeholder defined by curly braces followed by the format method where we passed the argument “Python” which got concatenated with the string object. These arguments inside format method can be anything integer, string, float or even variables. Similarly, we can pass the user name as an argument to get the following output:

We can also assign a string with a placeholder to a variable then call the variable with the format method along with the arguments like this,

Using multiple placeholders

There are no limits on the number of placeholders a string can have, Placeholders will get replaced by the arguments in the order they are arranged. Look at the below example,

In multiple substitutions, the arguments of the format method are separated by a comma(,) and they replace the {} in the same order they are arrayed. We can also assign values to a variable then call them inside format method like this:

Positional Arguments

Till now we have only used empty placeholders {}. However, we can also pass arguments within them. We have already seen that, if we keep placeholders empty then Python will replace them with values present in the format method in arrayed order. This default nature can be changed by passing the index of the argument inside the curly braces.

Here we passed the index of the arguments in the reverse order, so the first pair of curly braces gets substitute by the second argument and the second one by the first argument. The values inside the format method are nothing but the tuple data type, which can be called by the index numbers, keep in mind the index starts from 0. If we try to call an index which doesn’t exist, we will get an error like this,

Keyword arguments

Keyword arguments are essentially variables storing some value that are passed into the placeholder as a parameter. Sometimes parameters are also referred as Keyword name.

Keyword arguments along with positional arguments can be used on a single String object

Specifying Type

Conversion of a Value using the format method is also possible. Use the format code syntax {field_name:conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type. Conversion code is the single character python code used in Python, which are

s – strings
d – decimal integers (base-10)
f – floating point display
c – character
b – binary
o – octal
x – hexadecimal with lowercase letters after 9
X – hexadecimal with uppercase letters after 9
e – exponent notation

Let’s convert an integer value to float,

By adding :f inside the curly braces, we turned our integer to a float number. By default Python will put 6 digits after the decimal we can change that too;

We limited the places after the decimal to 2 just by adding .2 inside the curly braces.

Add padding

As we can observe, Placeholders are getting replaced by the arguments. Meanwhile, we can also add padding around them. Padding is nothing but some extra space around the text.

Here we added extra ten-character padding inside the placeholders in order to get an extra 10 character space. We can also modify the alignment of the values inside the string. (<) will left- align the text and (>) will right-align the text and (^) will center the text. Pass these parameters just after the colon and before the padding like this:

But when should one use this padding property? Well, Formatters are generally used to organize data in a readable way. This can be better understand by the following example,

This gave us the following output

We are getting our desired output but the data is not much appealing, we can add some padding to make our data more organized.

Now our data looks better rather say organized. There are plenty of other things we can do with the format method like Dictionary keys can be used as arguments as well:

The same applies to list and tuple indices:

How To Use String Formatting In Python

Next Recommended Article: Feature, Uses, and Advantages of TUPLE in Python

The article was published on September 19, 2020 @ 11:20 AM

Leave a Comment