Skip to content

Python f-string format specifier

  • by

Python f-string format specifier has an f prefix and uses {} brackets to evaluate values. Where Format specifiers for types, padding, or aligning are specified after the colon character.

Python f-string format specifier

Simple example code string formatting in Python.

name = 'John'
age = 25

print('%s is %d years old' % (name, age))
print('{} is {} years old'.format(name, age))
print(f'{name} is {age} years old')

Output:

Python f-string format specifier

f-string expressions

You can put expressions between the {} brackets.

bags = 3
apples_in_bag = 12

print(f'There are total of {bags * apples_in_bag} apples')

Output: There are total of 36 apples\

f-string dictionaries

user = {'name': 'John Doe', 'occupation': 'gardener'}

print(f"{user['name']} is a {user['occupation']}")

f-string debug

import math

x = 0.8

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

Multiline f-string

name = 'John Doe'
age = 32
occupation = 'gardener'

msg = (
    f'Name: {name}\n'
    f'Age: {age}\n'
    f'Occupation: {occupation}'
)

print(msg)

f-string format width

for x in range(1, 11):
    print(f'{x:02} {x*x:3} {x*x*x:4}')

Output:

01   1    1
02   4    8
03   9   27
04  16   64
05  25  125
06  36  216
07  49  343
08  64  512
09  81  729
10 100 1000

f-string justify string

s1 = 'a'
s2 = 'ab'
s3 = 'abc'
s4 = 'abcd'

print(f'{s1:>10}')
print(f'{s2:>10}')
print(f'{s3:>10}')
print(f'{s4:>10}')

Output:

         a
        ab
       abc
      abcd

Do comment if you have any doubts or suggestions on this Python string format topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *