IKH

Formatting The Strings

  • We can format the strings with variable values by using replacement operator {} and format() method.
  • The main objective of format() method to format string into meaningful output form.

Case – 1: Basic formatting for default, positional and keyword arguments

Python
name='ajay'
salary=1000
age=28
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))

Output

PowerShell
ajay 's salary is 1000 and his age is 28
ajay 's salary is 1000 and his age is 28
ajay 's salary is 1000 and his age is 28

Case – 2: Formatting Numbers

  • d ⇒ Integer
  • f ⇒ Float. The default precision is 6
  • b ⇒ Binary format
  • o ⇒ Octal Format
  • x ⇒ Hexa Decimal Format (Lower case)
  • X ⇒ Hexa Decimal Format (Upper case)

Example

Python
print("The int number is: {}".format(123))
print("The int number is: {:d}".format(123))
print("The int number is: {:5d}".format(123))
print("The int number is: {:05d}".format(123))

Output

PowerShell
The int number is: 123
The int number is: 123
The int number is:   123
The int number is: 00123

Example

Python
print("The float number is: {}".format(123.4567))
print("The float number is: {:f}".format(123.4567))
print("The float number is: {:8.3f}".format(123.4567))
print("The float number is: {:08.3f}".format(123.4567))
print("The float number is: {:08.3f}".format(123.45))
print("The float number is: {:08.3f}".format(786786123.45))

Output

PowerShell
The float number is: 123.4567
The float number is: 123.456700
The float number is:  123.457
The float number is: 0123.457
The float number is: 0123.450
The float number is: 786786123.450

Remark

Syntax

Python
{:08.3f}
  • Total positions should be minimum 8.
  • After decimal point exactly 3 digits are allowed. If it is less then 0s will be placed in the last positions.
  • If total number is < 8 positions then 0 will be placed. If total number is > 8 positions then all int digits will be considered.
  • The extra digits we can take only 0.

Remark

  • For numbers default alignment is Right Alignment (>).

Question

Print decimal value in binary, octal and hexadecimal form

Python
num=342
print("Binary Form:{0:b}".format(num))
print("Octal Form:{0:o}".format(num))
print("Hexa decimal Form:{0:x}".format(num))
print("Hexa decimal Form:{0:X}".format(num))

Output

PowerShell
Binary Form:101010110
Octal Form:526
Hexa decimal Form:156
Hexa decimal Form:156

Remark

  • {:5d} ⇒ It takes an int argument and assigns a minimum width of 5.
  • {:8.3f} ⇒ It takes a float argument and assigns a minimum width of 8 including “.” and after decimal point exactly 3 digits are allowed with round operation if required.
  • {:05d} ⇒ The blank places can be filled with 0. In this place only 0 allowed.

Case – 3: Number formatting for signed numbers

  • While displaying positive numbers, if we want to include + then we have to write {:+d} and {:+f}.
  • Using plus for -ve numbers there is no use and for -ve numbers – sign will come automatically.

Example

Python
print("int value with sign:{:+d}".format(123))
print("int value with sign:{:+d}".format(-123))
print("float value with sign:{:+f}".format(123.456))
print("float value with sign:{:+f}".format(-123.456))

Output

PowerShell
int value with sign:+123
int value with sign:-123
float value with sign:+123.456000
float value with sign:-123.456000

Case – 4: Number formatting with alignment

  • <,>,^, = ⇒ Used for alignment
    • < ⇒ Left Alignment to the remaining space2
    • ^ ⇒ Center alignment to the remaining space
    • = ⇒Right alignment to the remaining space
    • = ⇒ Forces the signed (+) (-) to the left most position

Remark

  • Default Alignment for numbers is Right Alignment.

Example

Python
print("{:5d}".format(12))
print("{:<5d}".format(12))
print("{:<05d}".format(12))
print("{:>5d}".format(12))
print("{:>05d}".format(12))
print("{:^5d}".format(12))
print("{:=5d}".format(-12))
print("{:^10.3f}".format(12.23456))
print("{:=8.3f}".format(-12.23456))

Output

PowerShell
   12
12   
12000
   12
00012
 12  
-  12
  12.235  
- 12.235

Case – 5: String formatting with format()

  • Similar to numbers, we can format String values also with format() method.

Syntax

Python
str.format(my_string)

Example

Python
print("{:5}".format("rat"))
print("{:>5}".format("rat"))
print("{:<5}".format("rat")) 
print("{:^5}".format("rat")) 
print("{:*^5}".format("rat"))

Output

PowerShell
rat  
  rat
rat  
 rat 
*rat*

Remark

  • For numbers default alignment is right where as for strings default alignment is left .

Case-6: Truncating Strings with format() method

Example

Python
print("{:.3}".format("internetknowledgehub"))
print("{:5.3}".format("internetknowledgehub"))
print("{:>5.3}".format("internetknowledgehub"))
print("{:^5.3}".format("internetknowledgehub"))
print("{:*^5.3}".format("internetknowledgehub"))

Output

PowerShell
int
int  
  int
 int 
*int*

Case-7: Formatting dictionary members using format()

Example

Python
person={'age':28,'name':'amit'}
print("{p[name]}'s age is: {p[age]}".format(p=person))

Output

PowerShell
amit's age is: 28

Example

Python
person={'age':28,'name':'amit'} 
print("{name}'s age is: {age}".format(**person))

Output

PowerShell
amit's age is: 28

Case-8: Formatting class members using format()

Example

Python
class Person:
  age=28
  name="amit"
print("{p.name}'s age is :{p.age}".format(p=Person()))

Output

PowerShell
amit's age is :28

Example

Python
class Person:
  def __init__(self,name,age):
    self.name=name
    self.age=age
print("{p.name}'s age is :{p.age}".format(p=Person('amit',26)))
print("{p.name}'s age is :{p.age}".format(p=Person('ajay',28)))

Output

PowerShell
amit's age is :26
ajay's age is :28

Remark

  • Here Person object is passed as keyword argument. We can access by using its reference variable in the template string.

Case-9: Dynamic Formatting using format()

Example

Python
string="{:{fill}{align}{width}}"
print(string.format('cat',fill='',align='^',width=5))
print(string.format('cat',fill='',align='^',width=6))
print(string.format('cat',fill='',align='<',width=6))
print(string.format('cat',fill='',align='>',width=6))

Output

PowerShell
 cat 
 cat  
cat   
   cat

Case-10: Dynamic Float format template

Example

Python
num="{:{align}{width}.{precision}f}"
print(num.format(123.236,align='<',width=8,precision=2))
print(num.format(123.236,align='>',width=8,precision=2))

Output

PowerShell
123.24  
  123.24

Case-11: Formatting Date values

Example

Python
import datetime
date=datetime.datetime.now()
print("It's now:{:%d/%m/%Y %H:%M:%S}".format(date))

Output

PowerShell
It's now:14/09/2023 05:30:50

Case-12: Formatting complex numbers

Example

Python
complexNumber=9+7j
print("Real Part:{0.real} and Imaginary Part:{0.imag}".format(complexNumber))

Output

PowerShell
Real Part:9.0 and Imaginary Part:7.0

Ungraded Questions

Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!


Name
Email
Phone

Report an error