String Formatting in Python

In this tutorial, we will learn about string formatting or how to format string in Python with the help of examples.

String formatting is a way to present a string value to provide a better view on the console. It produces a more readable and interesting output on the console.

Sometimes, it is also called string interpolation because it interpolates string literal and converts values. There are several different ways to perform string formatting in Python. They are as:

  • Formatting with % Operator.
  • Formatting with format() string method.
  • Formatting with string literals, called f-strings

Let’s understand each way to format string with the help of examples.

String Formatting with % Operator in Python


This is the oldest and easiest method of string formatting in Python. We can use a format operator (%) to perform string formatting operations. When we use the % sign with numbers in the print statement, it works as a remainder operation.

With strings, it works as a string formatting operator. The general syntax to use string formatting operator is as:

<string> % <values>

Here is a table of all the symbols that we can use alongside % to format string.

Format symbolConversion
%ccharacter
%dsigned decimal integer
%isigned decimal integer
%uunsigned decimal integer
%ffloating point real number
%sstring conversion using str() before formatting
%eexponential notation (with lowercase ‘e’)
%Eexponential notation (with uppercase ‘E’)
%xhexadecimal integer (lowercase letters)
%Xhexadecimal integer (uppercase letters)
%gthe shorter of %f and %e
%Gthe shorter of %f and %E
%ooctal integer

Let’s take some important examples based on the above format operator.


Example 1: Use of %c operator

print('ASCII character of 66 is %c'%66)
Output:
      ASCII character of 66 is B

In this example, %c prints the ASCII character of an integer value 66. It basically converts a single character string as well as an integer value to the corresponding ASCII character.

Example 2: Use of %s operator

age = 22
print('My age is %s'%age)
Output:
      My age is 22

%s is used to convert any type of value into string format. Here, we have used %s to insert or put the value of variable age into a string. The %s is replaced by the argument value and print it.


Example 3:

first_name = 'John'
last_name = 'Harry'
print('My name is %s %s'%(first_name, last_name))
Output:
      My name is John Harry

In this example, the (first_name, last_name) is a tuple and the complete expression is transformed into a string with the help of %s. The first %s is replaced by the value of “first_name” and the second %s is replaced by the value of “last_name”. All the other characters in the string stay as they are.

Example 4: Usage of %i and %d

num1 = 20.456
num2 = 30.5768
print('First number is %i'%num1)
print('Second number is %d'%num2)
Output:
      First number is 20
      Second number is 30

We can also perform string formatting with integer by using %i or %d instead of %s. In the above example, we have assigned the values of num1 and num2 in the form of decimal, but formatting string %i and %d print only the integer part of the variable’s value.

Example 5: Usage of %f or %F

per1 = 80.4567
print('My first term percentage is %f' %per1)
per2 = 80.4546
print('My second term percentage is %.2F' %per2)
Output:
      My first term percentage is 80.456700
      My second term percentage is 80.45

In this example, the %f string formatting prints the decimal value to six decimal places. The .”.2″ modifier of %F truncates the decimal value up to two decimal places and prints it.

We can also use other format symbols like + (to display the +ve sign), – (for left justification). Let us take an example of it.

Example 6:

num = 90.5464
print("Number with sign: %+f" %num)
Output:
      Number with sign: +90.546400

Example 7: Usage of %x and %o

num = 27
print(f"Hexadecimal representation of {num}: %x" %num)
print(f"Octal representation of {num}: %o" %num)
Output:
      Hexadecimal representation of 27: 1b
      Octal representation of 27: 33

Example 8:

name = "John"
print("Name: %10s"%(name))
Output:
      Name:       John

In this example, %10s means formatting the first value as a string with a space of 10 digits. So, the output shows 6 leading spaces with 4 characters of string.

String Formatting using format() Method


String class also provides a method named format() to format string in Python. It is a newer and most popular method of formatting strings to produce more readable output on the console.

In this method, we use curly braces ({ }) as placeholders to enclose strings format objects. The general syntax to use format() function of string class is as:

String.format(parameters)

In the above syntax, String is an object that has to be formatted. Parameters are values or objects to be formatted and starting from default position {0}.

Let’s take some important example programs based on it.

Example 9:

my_name = input("Enter your name: ")
print("My name is {}".format(my_name))
Output:
       Enter your name: John
       My name is John

In this example, we have taken the name of user as input by using input() function and stored in the variable my_name. Then, we have called the format() method on the string literal with passing the value of my_name which are interpolated, in order, into the locations of replacement fields, indicated by empty curly braces, ({ }).

Example 10:

name = "John"
age = 22
id = 23424
print("Name: {}, Age: {}, Id: {}".format(name, age, id))
Output:
      Name: John, Age: 22, Id: 23424

Example 11:

name = "Bob"
age = 22
id = 35465
print("{} {} {}".format(name, age, id))
Output:
      Bob 22 35465

In this example, we have called format() method on the string literal by passing argument values of name, age, and id which are interpolated in default order into the locations indicated by curly braces.

Note that by default, values are displayed in the order in which they are positioned as arguments in the format() function.


However, we can set the positional order different from their default positional order to substitute string values or objects. To set the order, we have to specify their index of argument values inside the curly braces.

Indexing begins from zero. The first value has index o, the second one has index 1, and so on. Let us take an example of it.

Example 12:

n1 = "Mark"
n2 = "John"
n3 = "Harry"
# Default order.
print("Students by default order: ")
print("{}, {}, {}".format(n1, n2, n3))

print("Students by positional order: ")
# Setting the order of positions. 0, 1, 2 are order parameters. 
print("{1}, {0}, {2}".format(n1, n2, n3))
Output:
      Students by default order: 
      Mark, John, Harry
      Students by positional order: 
      John, Mark, Harry

We can set string values or objects by using keyword arguments passed to the format() function. Let’s take an example to understand better.

Example 13:

n1 = "Mark"
n2 = "John"
n3 = "Harry"
print("Students by default order: ")
print("{}, {}, {}".format(n1, n2, n3))

print("Students by keyword order: ")
print("{h}, {j}, {m}".format(h = n3, j = n2, m = n1))
Output:
      Students by default order: 
      Mark, John, Harry
      Students by keyword order: 
      Harry, John, Mark

Space, Alignment, Rounding using format() function


Space, alignment, and rounding are also possible using format() function of string class. There are the following optional formatting specifications. They are:

  • For left alignment: greater than (<) sign
  • For right alignment: less than (>) sign
  • For center alignment: (^) sign
  • For rounding: dot (.)

Let’s take some example programs based on these points.

Example 14:

item_no = 2313
price = 155.6287
print("Item no.: {0:8d} \nPrice per piece: {1:8.2f}".format(item_no, price))
Output:
      Item no.:     2313 
      Price per piece:   155.63

In this example, {0:8d} means to format the first argument as integer with a space of 8 digits. So, the output shows 4 leading spaces to match the actual 4 digits with the given value, 2313.

{1:8.2f} means to format the second argument as float with 8 digits and 2 decimal places. Since the value shows up to 6 digits, 2 leading spaces has added in the output. In addition to it, the 4 decimal places has rounded off to 2.


Example 15:

name = "John"
print("Name: {0:>10s}".format(name)) # right alignment.
print("Name: {0:<10s}".format(name)) # left alignment.
print("Name: {0:^10s}".format(name)) # center alignment.
Output:
      Name:       John
      Name: John      
      Name:    John 

In this example, {0:>10s}, {0:<10s}, and {0:^10s} means formatting the first argument as string with right alignment, left alignment, and center, respectively.

Formatting String Literals using f-strings


Python 3.6 has introduced a new string formatting mechanism called f-strings (short for formatted string literals). This mechanism is quite cool and is faster than using format() method and % formatting. It provides a more convenient way to create formatted strings.

An f-string is a string literal, prefixed with ‘f’, which contains expressions inside the pair of curly braces ({ }). To create an f-string, first write the character f immediately preceding a string literal.

Within string literal, enclose expressions in the pair of curly braces to put the value of expressions into the formatted string. The general syntax to create formatted string literals in Python is as:

f"string_statements {variable_name [:{width}.{precision}]}"

Let’s take some examples based on string formatting using f-strings in Python.

Example 16:

name = "Harry"
age = 22
sName = "RSVM"
print(f"{name}, {age}, {sName}")
Output:
      Harry, 22, RSVM

Example 17: 

name = "Harry"
age = 22
print(f"Hello! My name is {name} and I'm {age} years young.")
Output:
      Hello! My name is Harry and I'm 22 years young.

We can also perform arithmetic operations using f-strings.

Example 18:

n1 = 23
n2 = 45
n3 = 55
print(f"Sum of three numbers = {n1 + n2 + n3}")
Output:
      Sum of three numbers = 123

It is also possible to use lambda expressions in f-string formatting.

Example 19:

print(f"He said I am {(lambda x: x * 2) (10)} years young.")
Output:
      He said I am 20 years young.

Example 20:

width = 10
precision = 5
value = 15.57685
print(f"result = {value:{width}.{precision}}")
print(f"result = {value:{width}}")
print(f"result = {value:{precision}}")
Output:
       result =    15.577
       result =  15.57685
       result = 15.57685

In this example, we have created a string statement named result. Within the curly braces, we have specified a variable named value whose value will be displayed. We have specified both width and precision within the curly braces.

Colon separates the variable with either width or precision values. Width value creates a space around variable value. Precision specifies the total number of digits including decimal point that will be displayed.


In this tutorial, you have learned about string formatting in Python with various examples. I hope that you will have understood the basic concepts of all methods of formatting string.
Thanks for reading!!!