Skip to content

Python f string padding | Example code

  • by

Python f string padding With the introduction of formatted string literals (“f-strings” for short) in Python 3.6, it is to access previously defined variables with a briefer syntax:

f'{num:{fill}{width}}'

Python f-string padding spaces code example

Simple example code.

String padding

name = 'Peter'
age = 23

print(f'{name} is {age:3} years old')

Output:

Python f string padding

String format zero-padded int python

i = 89
s = f'{i:03}'
print(s)

s = f'{i:15}'
print(s)

Output:

String format zero-padded int python

Python f string padding in for loop

for n in range(2):
    print(f'The number is {n:4}')

Output:

The number is 0
The number is 1

Do comment if you have any doubts and suggestions on this Python f string tutorial.

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 *