1

I'm a newbie in python.

I am stuck at figuring out fstring workings

Example 1

for n in range(1,11):
    sentence = f"The value is {n:{n:1}}"
    print(sentence)

Output:

The value is 1
The value is  2
The value is   3
The value is    4
The value is     5
The value is      6
The value is       7
The value is        8
The value is         9
The value is         10

Example 2

for n in range(1,11):
    sentence = f"The value is {n:{n:02}}"
    print(sentence)

Output:

The value is 1
The value is 02
The value is 003
The value is 0004
The value is 00005
The value is 000006
The value is 0000007
The value is 00000008
The value is 000000009
The value is         10

Example 3

for n in range(1,11):
    sentence = f"The value is {n:{n:03}}"
    print(sentence)

Output:

The value is 1
The value is 02
The value is 003
The value is 0004
The value is 00005
The value is 000006
The value is 0000007
The value is 00000008
The value is 000000009
The value is 0000000010

What I really want to know is How fstring interprets width & precision? Why example 2 last loop hasn't been calculated with zero paddings?

If I am not wrong, Example 1 output is interpreted as width. Example 2 & Example 3 is padding zero.

Also, How I can code to get the width with zero paddings like this? Require Output:

The value is   01
The value is   02
The value is   03
The value is   04
The value is   05
The value is   06
The value is   07
The value is   08
The value is   09
The value is   10

2 Answers 2

1

You could do:

for n in range(1,11):
    n = f'{n:0>2}'
    sentence = f"The value is {n:>5}"
    print(sentence)

{n:0>2} means pad with zero in front if n has digital less than two, while {n:>5} mean pad with 5 spaces in front of n. See Python f-string Documentation

Sign up to request clarification or add additional context in comments.

Comments

0
for n in range(1,11):
sentence = f"The value is {n:02}"
print(sentence)

You can change {n:02} to {n:03} or other to check the difference.

{n:0x} print a hex format.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.