DEV Community

Cover image for #Day17 - Fastest way to format strings in Python
Rahul Banerjee
Rahul Banerjee

Posted on • Originally published at realpythonproject.com

#Day17 - Fastest way to format strings in Python

There are 3 ways to format strings in Python

  • Using the % operator
  • Using format()
  • Using f strings

image.png

We have three functions

  • func1 uses the % operator
  • func2 uses format()
  • func3 uses f strings

We will use the timeit function to measure the time taken by each function

image.png

We call each function 100 times and calculate the average time taken for the function call. The average time is stored in a list.

image.png

Below are the comparisons of the 3 functions

download.png

As you can see, f strings are faster as compared to format() and the % operator.

if.....else with f strings

num = 2
print(f"{num} is an {'even' if num%2 ==0 else 'odd'} number")

num = 3
print(f"{num} is an {'even' if num%2 ==0 else 'odd'} number")
Enter fullscreen mode Exit fullscreen mode

Aligning strings

  • Left-aligned: {variable :> number}
  • Center-aligned: {variable :^ number}
  • Right-aligned: {variable :< number}
text = "string"
print(f'{text:>20}')
print(f'{text:^10}')
print(f'{text:<30}')

'''
OUTPUT
              string
  string  
string  
'''
Enter fullscreen mode Exit fullscreen mode

Round floating points

num =  20.012345783
print(f'{num:0.3f}')

'''
OUTPUT
20.012
'''
Enter fullscreen mode Exit fullscreen mode

Pad Zeroes

x = 10
print(f'{x:0}') #10
print(f'{x:02}') #10
print(f'{x:03}') #010
print(f'{x:04}') # 0010
Enter fullscreen mode Exit fullscreen mode

If you want to pad n zeroes to a y digit number, it should be

print(f'{x:0n+y}')
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
mohdaad89422253 profile image
Mohd Aadil

Thanks for sharing