Open In App

How to use string formatters in Python ?

Last Updated : 01 Oct, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The output displayed as a result of a program should be organized in order to be readable and understandable. The output strings can be printed and formatted using various ways as listed below.

  1. Using print()
  2. Using format specifiers.
  3. Using format() method.
  4. Using formatted string literal (f-string).

This article covers the first three methods given above.

Using print()

The print() function is used to display any message or output of processes carried out in Python. This function can be used to print strings or any object. But, before printing the object that is not of string type, print() converts it to a string. The string can be formatted either with the parameters of this method itself or using the rest of the methods covered in this article. The separator parameter (sep) of this function can help to display the desired symbol in between each element being printed. 

Example: Printing the swaps in each iteration while arranging a list in ascending order

Python3




# initialize the list
li = [1, 4, 93, 2, 3, 5]
  
print("Swaps :")
  
# loop for arranging
for i in range(0, len(li)):
  
    for j in range(i+1, len(li)):
  
        # swap if i>j
        if li[i] > li[j]:
            temp = li[j]
            li[j] = li[i]
            li[i] = temp
  
            # print swapped elements
            print(li[i], li[j], sep="<--->")
  
print("Output :", li)


Output

Swaps :
2<--->4
4<--->93
3<--->4
4<--->93
5<--->93
Output : [1, 2, 3, 4, 5, 93]

Using format specifiers

The format specifiers are the ones that we use in languages like C-programming. Python does not have a printf() as in C, but the same functionality is provided here. The modulo operator (‘%’) is overloaded by the string class for formatting the output. The % operator formats the set of variables contained within a tuple. If multiple format specifiers are chained, then the first specifier acts on the 0th element in the tuple, the second acts on 1st  element in the tuple and so on. The format specifiers are given in the table below.

Format specifier

                             Description                                        

%s

Specifies the String

%c

Specifies a single character

%d

Specifies the integer

%f

Specifies the float. Any number of digits can be present after decimal point

%<space>.<number>f

Specifies the float. <space> denotes the number of space to append before printing the number.

 <number> denotes the number of digits to be present after the decimal point.

%x / %X

Specifies the hexadecimal representation of the value

%o

Specifies the octal representation of a value

%e / %E

Specifies the floating numbers in exponential format

%g / %G

Similar to %e/%E. Specifies the exponential format only if the exponent is greater than -4

Example:

Python3




# string
st = "This is a string"
print("String is %s" % (st))
  
# single character
ch = 'a'
print("Single character is %c" % (ch))
  
# integer
num = 45
print("The number is %d" % (num))
  
# float without specified precision
float1 = 34.521094
print("The float is %f" % (float1))
  
# float with precision
float2 = 7334.34819560
print("The float with precision is %.3f" % (float2))
  
# multiple specifiers in print()
# Hexa decimal representation
print("The hexadecimal form of %d is %x" % (num, num))
  
# octal representation
print("The octal form of %d is %o" % (num, num))
  
# exponential form
print("The exponential form of %f is %e" % (float1, float1))
  
# exponential form with appended space
print("The exponential form of %f is %10.3g" % (float2, float2))
  
# exponent less than -4 with appended space
float3 = 3.14
print("The exponential form of %.2f is %10.3g" % (float3, float3))


Output

String is This is a string
Single character is a
The number is 45
The float is 34.521094
The float with precision is 7334.348
The hexadecimal form of 45 is 2d
The octal form of 45 is 55
The exponential form of 34.521094 is 3.452109e+01
The exponential form of 7334.348196 is   7.33e+03
The exponential form of 3.14 is       3.14

Using format() method

format() is one of the methods in string class which allows the substitution of the placeholders with the values to be formatted. 

Syntax : { }…..{ } . format ( args )

Parameters:

  • { } – Placeholders to hold index/keys. Any number of placeholders are allowed to be placed.
  • args – Tuple of values to be formatted.

The parameters are categorized into two types namely :

  • Positional – The index of the object to be formatted will be written inside the placeholders.
  • Keyword The parameters will be of key=value type. The keys will be written inside the placeholders.

Type-specific formatting can also be performed using this method. The datetime objects, complex numbers can also be formatted using this method.

Example:

Python3




# complex number
c = complex(5+9j)
  
# without format() method
print("Without format() - Imaginary :", str(c.imag), " Real :", str(c.real))
  
# with format() method
print("With format() - Imaginary : {} Real : {}".format(c.imag, c.real))


Output

Without format() - Imaginary : 9.0  Real : 5.0
With format() - Imaginary : 9.0 Real : 5.0

The format() method can be overridden with the help of classes and dunder methods.

Python3




# class for holding person's details
class person:
  
    # constructor
    def __init__(self, name, age, des):
        self.name = name
        self.age = age
        self.des = des
  
    # overriding format()
    def __format__(self, f):
  
        if f == 'name':
            return "I am "+self.name
  
        if f == 'age':
            return "My age is "+str(self.age)
  
        if f == 'des':
            return "I work as "+self.des
  
  
p = person('nisha', 23, 'manager')
print("{:name}, {:age}".format(p, p))
print("{:des}".format(p))


Output

I am nisha, My age is 23
I work as manager

Using f-string

This method was introduced in Python 3.6 version. This is much easier than using a format specifier or a format() method. The f-strings are expressions that are evaluated in the runtime and are formatted by the __format__() method. For formatting a string using the f-string, the formatting expression must be written in quotes preceded by ‘f’/’F’.

Syntax : f “<text> {placeholder} <text>” or F”<text> {placeholder} <text>”

Example 1

The name and age are variables. They can be formatted and printed with the help of f-string by placing the variable in the appropriate placeholders. The placeholders are just the curly braces found within the texts.

Python3




name = "Rinku"
age = 20
  
print(f"Hi! my name is {name} and my age is {age}")


Output

Hi! my name is Rinku and my age is 20

Example 2:

Expressions can also be evaluated and displayed using this f-string method.

Python3




a = 5
b = 6
  
print(F"Addition : {a+b}")
print(F"Subtraction : {a-b}")
print(F"Multiplication : {a*b}")
print(F"Division without roundoff : {a/b}")
print(F"Division with roundoff : {round(a/b,3)}")


Output

Addition : 11
Subtraction : -1
Multiplication : 30
Division without roundoff : 0.8333333333333334
Division with roundoff : 0.833

Example 3:

Even functions can be called from the f-string placeholders. A function to evaluate the expression a2 + 3b2 + ab is defined and called within the placeholder.

Python3




# f function to evaluate expression
def exp_eval(a, b):
    ans = (a*a)+(3*(b*b))+(a*b)
    return ans
  
  
# values to be evaluated
a = 2
b = 4
  
# formatting
print(f"The expression a**2+3b**2+(a*b) = {exp_eval(a,b)}")


Output

The expression a**2+3b**2+(a*b) = 60


Previous Article
Next Article

Similar Reads

Use of nonlocal vs use of global keyword in Python
Prerequisites: Global and Local Variables in PythonBefore moving to nonlocal and global in Python. Let us consider some basic scenarios in nested functions. C/C++ Code def fun(): var1 = 10 def gun(): print(var1) var2 = var1 + 1 print(var2) gun() fun() Output: 10 11 The variable var1 has scope across entire fun(). It will be accessible from nested f
3 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
String slicing in Python to Rotate a String
Given a string of size n, write functions to perform following operations on string. Left (Or anticlockwise) rotate the given string by d elements (where d &lt;= n).Right (Or clockwise) rotate the given string by d elements (where d &lt;= n).Examples: Input : s = "GeeksforGeeks" d = 2Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeek
3 min read
Python | Check if given string can be formed by concatenating string elements of list
Given a string 'str' and a list of string elements, write a Python program to check whether given string can be formed by concatenating the string elements of list or not. Examples: Input : str = 'python' lst = ['co', 'de', 'py', 'ks', 'on'] Output : False Input : str = 'geeks' lst = ['for', 'ge', 'abc', 'ks', 'e', 'xyz'] Output : True Approach #1
5 min read
Python | Check if string ends with any string in given list
While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string ends with any of the matching strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using filter() + endswith() The combination of the above func
6 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
Python | Merge Tuple String List values to String
Sometimes, while working with records, we can have a problem in which any element of record can be of type string but mistakenly processed as list of characters. This can be a problem while working with a lot of data. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehension + join() The combination of abov
6 min read
Python | Sort each String in String list
Sometimes, while working with Python, we can have a problem in which we need to perform the sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let's discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension + sorted() + join() This is
4 min read
Python | Convert List of String List to String List
Sometimes while working in Python, we can have problems of the interconversion of data. This article talks about the conversion of list of List Strings to joined string list. Let's discuss certain ways in which this task can be performed. Method #1 : Using map() + generator expression + join() + isdigit() This task can be performed using a combinat
6 min read
Python - Length of shortest string in string list
Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum length string of all the strings in list. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this task can be performed. Method #1 : Using min() + generator expression The combination of the above f
5 min read
Article Tags :
Practice Tags :