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 formats available like %-formatting, str.format(), or string.Template(). The main disadvantage of using these existed is that it is not well – easy to execute the implementation, so Python added up f-string due to its easiness of implementation with minimal syntax.

Consider this for example for all the 3 variants :
1. Using %-formatting

filter_none

edit
close

play_arrow

link
brightness_4
code

name = 'nightfury1'
print('%s is GeeksforGeeks a contributor' % (name))

chevron_right


Output :

nightfury1 is GeeksforGeeks a contributor.

2. Using str.format()



filter_none

edit
close

play_arrow

link
brightness_4
code

name = 'nightfury1'
print('{} is GeeksforGeeks a contributor.'.format(name))

chevron_right


Output :

nightfury1 is GeeksforGeeks a contributor.

3. Using f-string

filter_none

edit
close

play_arrow

link
brightness_4
code

name = 'nightfury1'
print(f'{name} is GeeksforGeeks a contributor.')

chevron_right


Output :

nightfury1 is GeeksforGeeks a contributor.

Approaches using f-string :

1. f-string expressions : It evaluates the string inside {} and returns the value.

filter_none

edit
close

play_arrow

link
brightness_4
code

name = 'nightfury1'
post = 'Technical Content Writer Intern.'
print(f'{name} is GeeksforGeeks {post}')

chevron_right


Output :

nightfury1 is Geeksforgeeks Technical Content Writer Intern

2. f-string dictionaries : Since the dictionary contains key-value property. Hence, f-string use properties of a dictionary for string formatting.

filter_none

edit
close

play_arrow

link
brightness_4
code

GfG = {'name' : 'nightfury1',
       'post' : 'Technical Content Writer Intern'}
print(f'{GfG["name"]} is GeeksforGeeks {GfG["post"]}.')

chevron_right


Output:

nightfury1 is Geeksforgeeks Technical Content Writer Intern.

3. f-string debug : Debugging the value inside the given expression evaluates output.



filter_none

edit
close

play_arrow

link
brightness_4
code

import math
x = 0.5
   
print(f'math.cos({x}) = {math.cos(x)}')
print(f'math.sin({x}) = {math.sin(x)}')

chevron_right


Output :

math.cos(0.5) = 0.8775825618903728
math.sin(0.5) = 0.479425538604203

4. f-string multiline : The f-strings are placed between round brackets so it evaluates them, each of the string is preceded with the f character and returns the result in multiple lines.

filter_none

edit
close

play_arrow

link
brightness_4
code

name = 'nightfury1'
org = 'GeeksforGeeks'
post = 'Technical Content Writer Intern'
  
gfg = (f'Name : {name}\n'
       f'Organization : {org}\n'
       f'Post : {post}.')
  
print(gfg)

chevron_right


Output :

Name : nightfury1
Organization : GeeksforGeeks
Post : Technical Content Writer Intern.

Padding and filling using f-string :

We can input and specify the format with digits after decimal or certain given number or DateTime, this is called f-string padding.

1. 0-padding : Here, we apply 0-padding by adding {variable : 0N} inside the f-string {} syntax, where N refers the total no. of digits.

filter_none

edit
close

play_arrow

link
brightness_4
code

for i in range(1, 5):
    print(f'The number is {i:02}')

chevron_right


Output :

The number is 01
The number is 02
The number is 03
The number is 04

2. date-padding : Here, we also format the dates by using the DateTime module and adding up the desired format in {} like {date : directive}.

filter_none

edit
close

play_arrow

link
brightness_4
code

import datetime
now = datetime.datetime.now()
print(f'Current Time : {now : %Y-%m-%d %H:%M}')

chevron_right


Output:

Current Time :  2020-08-02 19:34

3. space-padding : Here, we apply spaces to a string like {variable : N} where N is total length. So if the given variable is ‘a’ and N is 4 then it will add extra spaces before the given variable.

filter_none

edit
close

play_arrow

link
brightness_4
code

for i in range(1, 5):
    print(f'The number is {i : 4}')

chevron_right


Output:



The number is    1
The number is    2
The number is    3
The number is    4

4. justify-padding : As we know that by default strings are justified to the left. But with the help f-strings, we can justify them right by using {variable : >N} where N is the total length.

filter_none

edit
close

play_arrow

link
brightness_4
code

s1 = 'Geeksforgeeks'
s2 = 'ksforgeeks'
s3 = 'forgeeks'
s4 = 'geeks'
  
print(f'{s1 : >13}')
print(f'{s2 : >13}')
print(f'{s3 : >13}')
print(f'{s4 : >13}')

chevron_right


Output :

Geeksforgeeks
   ksforgeeks
     forgeeks
        geeks

We can input and specify the format with digits or symbols before and after the given string, this is called f-string filling.

1. hardcoded – filling : Here we add the symbol or filler as hardcoded in f-string syntax.

filter_none

edit
close

play_arrow

link
brightness_4
code

# left filling
print(f'{"geeks" :*>15}')
  
# right filling
print(f'{"geeks" :*<15}')

chevron_right


Output:

**********geeks
geeks**********

2. variable – filling: Here we used f-string filling curly braces expression within the print() function.

filter_none

edit
close

play_arrow

link
brightness_4
code

width = 15
filler = '*'
for i in range(6, width):
    print(f'{"geeks" :{filler}<{i}}')

chevron_right


Output:

geeks*
geeks**
geeks***
geeks****
geeks*****
geeks******
geeks*******
geeks********
geeks*********

Advantages of f-strings :

  1. It is the fastest string formatting method in Python.
  2. It is more readable.
  3. It is concise in nature.
  4. It is less prone to error which means there are fewer chances of error while strings formatting.
  5. It is less verbose i.e., contains less syntax in formatting.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.