String Formatting using str.format method in Python

In this tutorial, we are going to learn how to format a string in python. Before diving into the topic let us gain some basic knowledge on string formatting using python.

String Formatting with Python:

A number and a string cannot be concatenated using a + symbol in python so we need a new method to do this and that new method is called the string.format(). Below is the output if you try to concatenate a string and number using the “+” symbol.

a=100
st="CodeSpeedy helps " + a + "% in solving problems"
print(st)

Output:

Traceback (most recent call last):                                                                                                              

  File "main.py", line 2, in <module>                                                                                                           

    st="CodeSpeedy helps " + a + "% in solving problems"                                                                                        

TypeError: Can't convert 'int' object to str implicitly

string.format():

String class which is part of Python provides the feature of intricate variable substitutions and its formatting using format() method.  format() method is a wrapper that internally invokes the vformat() method.

With the help of this format() method, we can perform multiple substitutions into the string at the same time. We can also concatenate elements within a string. The values that have to be added to the string are passed as tuples.

{} represents a placeholder (the special character that has to be replaced by the value).

The operations of this method can be broadly classified into 2:

  1. Concatenating values to a string
  2. Padding

Concatenating values to a string:

Concatenating 2 strings means adding a string at the end of the other.

We can concatenate 2 strings or a string and an integer with the help of the str.format method.

Syntax: template.format(values)

Here template is a string that includes {} in it. Where {} represents a placeholder (the special character that has to be replaced by the value).

Now that we know the basic syntax of the str.format method let us learn some of its features.

  1.  Single Formatter
  2.  Multiple Formatters
  3.  Formatter with keywords
  4.  Type-specific Formatter

Single Formatter:

As the word goes, in this type of formatting we will have only one format specifier. That means we use only one curly brace in the string.

Example 1:

st='This is an article on {}.'
print(st.format('string formatting'))

Output:

This is an article on string formatting.

 

Example 2:

a=100
print("This article is {}% student friendly".format(a))

Output:

This article is 100% student friendly

String Formatting using str.format method in Python

Multiple Formatters:

Multiple curly braces are used to insert multiple values in a string at the same time. The values will be replaced in the given order.

Example 1:

st='Todays date is {}, and time is {}'
print(st.format('28th June 2020','12am'))

Output:

Todays date is 28th June 2020, and time is 12am

Example 2:

print('{} {} cost {}rs'.format(6, 'bananas', 30))

Output:

6 bananas cost 30rs

Formatter with keywords:

The values that exist within the str.format() method are passed in as a tuple. So we can access them their index number.

Example 1:

print('{0} love {1}'.format('Programmers','Python'))
print('{1} love {0}'.format('Programmers','Python'))

Output:

Programmers love Python
Python love Programmers

Example 2:

print('{0} {1} cost {2}rs'.format(6, 'bananas', 30))

Output:

6 bananas cost 30rs

 

String Formatting using str.format method in Python

The placeholders can have arguments like ‘field_name’ and ‘conversion’.

  • field_name specifies the index number
  • conversion is the conversion code of the data type.

Conversion types:

  • s –> Strings.
  • d –> Integers.
  • f –> Floating-point.
  • c –> Character.
  • b –> Binary.
  • o –> Octal.
  • x –> Hexadecimal with lowercase letters.
  • X –> Hexadecimal with uppercase letters.
  • e –> Exponent notation.

Let us see these with examples given below

Example 1:

st='This site is {0:d}% {1:s}.'
print(st.format(100,'safe'))

Output:

This site is 100% safe.

Example 2:

print('{0:d} in binary is {0:b}'.format(10))

Output:

10 in binary is 1010

If a wrong type of value is given then, we encounter a ValueError.

st='This month the colony has used {0:d} units of electricity'
print(st.format(310.567))

Output:

Traceback (most recent call last):                                                                                                            

  File "main.py", line 2, in <module>                                                                                                         

    print(st.format(310.567))                                                                                                                 

ValueError: Unknown format code 'd' for object of type 'float'

Padding:

Adding a given character to the string to make it to a given length is called Padding.

Padding can be done using str.format by adding ‘<‘, ‘^’, and ‘>’ to the place holders.

  • ‘<‘    Adds the character to the left of the placeholder.
  • ‘^’   Adds the character to either side of the placeholder.
  • ‘>’    Adds the character to the right of the placeholder.

Example:

print('{0:>8s}'.format('Python'))
print('{0:<8d} {0}'.format(123))

Output:

  Python                                                                                                                                      

123      123

Example 2:

print('{0:-^18s}'.format('Thank you'))

Output:

----Thank you-----

With this, the tutorial is completed, I hope you have gained some knowledge through this tutorial.

Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *