Search code examples
pythonstringpython-2.7widthoperation

What is Python 's default setting for width on String Operations and how is it different that "0"?


I'm beginning to get into programming and cannot decipher yet the answer that I got from Python.org on this, and it looks like no one asked this question before.

I'm trying to figure out the difference between

"You have $%.2f left in your piggy bank" % totalCash

and

"You have $%0.2f left in your piggy bank" % totalCash

According to the book I am studying (Python Programming: An Introduction to Computer Science, by John Zelle): "You can use a 0 width to indicate "use as much space as needed." What doesn't make sense is, It is already using as much space as needed. If I put in that I have 100000.42 in my variable it still prints it with the correct amount of space regardless of whether or not I put the "0" as the width or not.

The output is identical.

So it seems to me that "0" the default width set, but then I looked at the documentation on Python.org and they say the same thing, but with some highly-technical words I don't understand

" Preceding the width field by a zero ('0') character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of '0' with an alignment type of '=' "

I don't understand that at all, but I do understand this next line which sounds like it is the same as what I thought the "0" did:

" width is a decimal integer defining the minimum field width. If not specified, then the field width will be determined by the content. "

So what is the difference, can anyone explain?

I am using Python 2.7


Solution

  • Note that neither is the correct way to do things now. Now we use string formatting, but a similar format exists.

    Basically, use of the 0 means if your DATA is shorter than your WIDTH, it will zero-fill to fill the width.

    >>> "{:8}".format(12)
    '      12'
    >>> "{:08}".format(12)
    '00000012'   # different when data is shorter than width
    >>> "{:8}".format(1234567890)
    '1234567890'
    >>> "{:08}".format(1234567890)
    '1234567890' # no difference when data is longer than width
    

    In old-style string interpolation, this would be:

    >>> "%8d" % 12
    '      12'
    >>> "%08d" % 12
    '00000012'
    >>> "%8d" % 1234567890
    '1234567890' # still no change
    >>> "%08d" % 1234567890
    '1234567890' # when data is longer than width