#Day17 - Fastest way to format strings in Python
Rahul Banerjee
Posted on April 7, 2021
There are 3 ways to format strings in Python
- Using the % operator
- Using format()
- Using f strings
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
We call each function 100 times and calculate the average time taken for the function call. The average time is stored in a list.
Below are the comparisons of the 3 functions
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")
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
'''
Round floating points
num = 20.012345783
print(f'{num:0.3f}')
'''
OUTPUT
20.012
'''
Pad Zeroes
x = 10
print(f'{x:0}') #10
print(f'{x:02}') #10
print(f'{x:03}') #010
print(f'{x:04}') # 0010
If you want to pad n zeroes to a y digit number, it should be
print(f'{x:0n+y}')
💖 💪 🙅 🚩
Rahul Banerjee
Posted on April 7, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
100daysofcode #Day23 - How to Scrape Websites using Requests and Beautiful Soup Part1
April 13, 2021