Pad or fill a string by a variable in Python using f-string - GeeksforGeeks (2024)

Last Updated : 18 Aug, 2020

Improve

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

name = 'nightfury1'

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

Output :

nightfury1 is GeeksforGeeks a contributor.

2. Using str.format()

name = 'nightfury1'

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

Output :

nightfury1 is GeeksforGeeks a contributor.

3. Using f-string

name = 'nightfury1'

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

Output :

nightfury1 is GeeksforGeeks a contributor.

Approaches using f-string :

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

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.

GfG = {'name' : 'nightfury1',

'post' : 'Technical Content Writer Intern'}

print(f'{GfG["name"]} is GeeksforGeeks {GfG["post"]}.')

Output:

nightfury1 is Geeksforgeeks Technical Content Writer Intern.

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

import math

x = 0.5

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

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

Output :

math.cos(0.5) = 0.8775825618903728math.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.

name = 'nightfury1'

org = 'GeeksforGeeks'

post = 'Technical Content Writer Intern'

gfg = (f'Name : {name}\n'

f'Organization : {org}\n'

f'Post : {post}.')

print(gfg)

Output :

Name : nightfury1Organization : GeeksforGeeksPost : 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.

for i in range(1, 5):

print(f'The number is {i:02}')

Output :

The number is 01The number is 02The number is 03The 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}.

import datetime

now = datetime.datetime.now()

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

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.

for i in range(1, 5):

print(f'The number is {i : 4}')

Output:

The number is 1The number is 2The number is 3The 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.

s1 = 'Geeksforgeeks'

s2 = 'ksforgeeks'

s3 = 'forgeeks'

s4 = 'geeks'

print(f'{s1 : >13}')

print(f'{s2 : >13}')

print(f'{s3 : >13}')

print(f'{s4 : >13}')

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.

# left filling

print(f'{"geeks" :*>15}')

# right filling

print(f'{"geeks" :*<15}')

Output:

**********geeksgeeks**********

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

width = 15

filler = '*'

for i in range(6, width):

print(f'{"geeks" :{filler}<{i}}')

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.


night_fury1

Improve

Next Article

Read a text file into a string variable and strip newlines in Python

Please Login to comment...

Pad or fill a string by a variable in Python using f-string - GeeksforGeeks (2024)
Top Articles
Latest Posts
Article information

Author: Ouida Strosin DO

Last Updated:

Views: 6537

Rating: 4.6 / 5 (56 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Ouida Strosin DO

Birthday: 1995-04-27

Address: Suite 927 930 Kilback Radial, Candidaville, TN 87795

Phone: +8561498978366

Job: Legacy Manufacturing Specialist

Hobby: Singing, Mountain biking, Water sports, Water sports, Taxidermy, Polo, Pet

Introduction: My name is Ouida Strosin DO, I am a precious, combative, spotless, modern, spotless, beautiful, precious person who loves writing and wants to share my knowledge and understanding with you.