The Wayback Machine - https://web.archive.org/web/20240905201926/https://www.geeksforgeeks.org/how-to-use-string-formatters-in-python/
Open In App

How to use string formatters in Python ?

Last Updated : 01 Oct, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 | 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
String Alignment in Python f-string
Text Alignment in Python is useful for printing out clean formatted output. Some times the data to be printed varies in length which makes it look messy when printed. By using String Alignment the output string can be aligned by defining the alignment as left, right or center and also defining space (width) to reserve for the string. Approach : We
2 min read
String to Int and Int to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting a string to int and int to string. Converting a string to an int If we want to convert a number that is represented in the string to int, we have to use the int() function. This function is used
2 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
Convert Unicode String to a Byte String in Python
Python is a versatile programming language known for its simplicity and readability. Unicode support is a crucial aspect of Python, allowing developers to handle characters from various scripts and languages. However, there are instances where you might need to convert a Unicode string to a regular string. In this article, we will explore five diff
2 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: [GFGTABS] Python string = &quot;Geeksforgeeks&quot; print(len(string)) [/GFGTABS]Output13String len() Syntaxlen(string) ParameterString: string of which you want to find the length. Retu
5 min read
Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
10 min read
When to use yield instead of return in Python?
The yield statement suspends a function's execution and sends a value back to the caller, but retains enough state to enable the function to resume where it left off. When the function resumes, it continues execution immediately after the last yield run. This allows its code to produce a series of values over time, rather than computing them at onc
2 min read
How to use a List as a key of a Dictionary in Python 3?
In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below . How does Python Dictionaries search their
3 min read
Use Pandas to Calculate Statistics in Python
Performing various complex statistical operations in python can be easily reduced to single line commands using pandas. We will discuss some of the most useful and common statistical operations in this post. We will be using the Titanic survival dataset to demonstrate such operations. C/C++ Code # Import Pandas Library import pandas as pd # Load Ti
6 min read
Use of min() and max() in Python
Prerequisite: min() max() in Python Let's see some interesting facts about min() and max() function. These functions are used to compute the maximum and minimum of the values as passed in its argument. or it gives the lexicographically largest value and lexicographically smallest value respectively, when we passed string or list of strings as argum
2 min read
Python | How to use Multiple kv files in kivy
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. In this article, we will see how can we use multiple .kv files in a single Application . This is the Python progra
3 min read
How to use multiple UX Widgets in kivy | Python
Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications. ???????? Kivy Tutorial - Learn Kivy with Examples. UX Widgets: Classical user interface widgets, ready to be assem
3 min read
Python program to find GSoC organisations that use a Particular Programming Language
Currently, it's not possible to sort GSoC participating organizations by the programming languages they use in their code. This results in students spending a lot of time going through each organization's page and manually sorting through them. This article introduces a way for students to write their own Python script using the BeautifulSoup4 libr
4 min read
How to use close() and quit() method in Selenium Python ?
While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the driver.dispose method that successively closes all the
2 min read
Use get() method to create a dictionary in Python from a list of elements
Prerequisites: Get() method for dictionaries in Python The naive approach for creating a dictionary from a list of items we can use the for loop. See the below example for better understanding. Example: li =['a', 'b', 'c', 'a', 'd', 'e', 'b', 'a'] di ={} for ele in li: # Increase the value of key # if exists if ele in di: di[ele]= di[ele]+1 else: #
2 min read
How to use Color Palettes in Python-Bokeh?
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh provides us with multiple color palettes in the bokeh.palettes module. Let us see how to use these colo
7 min read
How to use NamedTuple and Dataclass in Python?
We have all worked with classes and objects for more than once while coding. But have you ever wondered how to create a class other than the naive methods we have all been taught. Don't worry in this article we are going to cover these alternate methods. There are two alternative ways to construct a class in Python. NamedTuple DataClass First, of a
2 min read
How to use datasets.fetch_mldata() in sklearn - Python?
mldata.org does not have an enforced convention for storing data or naming the columns in a data set. The default behavior of this function works well with most of the common cases mentioned below: Data values stored in the column are 'Data’, and target values stored in the column are ‘label’.The first column table stores target, and the second sto
2 min read
How to use NumPy where() with multiple conditions in Python ?
In Python, NumPy has a number of library functions to create the array and where is one of them to create an array from the satisfied conditions of another array. The numpy.where() function returns the indices of elements in an input array where the given condition is satisfied. Syntax: numpy.where(condition[, x, y]) Parameters: condition : When Tr
3 min read
When not to use Recursion while Programming in Python?
To recurse or not to recurse, that is the question. We all know about the fun we have with recursive functions. But it has its own set of demerits too, one of which is going to be explained in this article to help you choose wisely. Say, we need to create a function which when called needs to print the data in a linked list. This can be done in 2 w
3 min read
How to use Thread in Tkinter Python
Prerequisite: Python GUI – tkintermultithreading Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create the GUI applica
2 min read
How to Use IF Statement in MySQL Using Python
Prerequisite: Python: MySQL Create Table In this article, we are going to see how to use if statements in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with
2 min read
How to use the Live Coding Feature of Python in Eclipse?
In this article, we'll be talking about how to use the Live Coding features of Python in Eclipse. Every time the programmer has to spend a lot of time debugging their code. And still, they failed to debug. This extension will help the coders or programmers to reduce their debugging time. This extension is downloadable in Eclipse IDE / PyCharm IDE.
2 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the server.The data in the Session is stored on the top o
4 min read
How to use HTML in Tkinter - Python?
Prerequisite: Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tki
2 min read
How to use Pickle to save and load Variables in Python?
Serialization is a technique used to save the state of an object from any process. We can later use this state by deserialization, to continue the process. Pickle is a python module that makes it easy to serialize or save variables and load them when needed. Unlike JSON serialization, Pickle converts the object into a binary string. JSON is text sp
2 min read
Article Tags :
Practice Tags :