Question about formating an integer such as "%02d"

hello everyone, please pardon me if this question seems dull, i’m very new to python, and couldn’t find an awnser online.

I just got out of the formating with % exercise, and there is something I don’t quite get.

I understood that when using a string with the % operator, the code will look for the value in the left end to replace the strings that start with a % by the said value.

but when it comes to integers, I don’t quite get how the syntax works.

I think i’m right by saying that “%02d” will provide 0 empty space between the replaced value and the string, and will make sure that the value is at minimum 2 digit wide, so that "the test result is %02d" % 5 will result in "the test result is 05"

but let’s say that for some reason I need to provide 1 empty spaces before the replaced value and make sure that the said replace value is 2 digit wide. Instinctively, i’d write "the test result is %12d" % 5 resulting in

"the test result is            5"

since the code understand 1-2 as 12, which makes perfect sense,

to sum it up, how do I differentiate the “white spaces” of my formating value to the “minimum digit” ?

Thanks a lot for your awnsers.

String Formatting with %, Part 1

>>> "the test result is %12d" % 5
'the test result is            5'
>>> "the test result is %012d" % 5
'the test result is 000000000005'
>>> "the test result is %-12d" % 5
'the test result is 5           '
>>> "the test result is %+12d" % 5
'the test result is           +5'
>>> "the test result is %12s%-12d" % ('',5)
'the test result is             5           '

The new .format() method offers many more options. % strings have a limited number of formatting characters.

Python String Formatting


Ooh, I get it now, i’ll look into .format .
Thanks a bunch !


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.