Monday, November 18, 2024
Google search engine
HomeLanguagesHow to use string formatters in Python ?

How to use string formatters in Python ?

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
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments