Python Forum

Full Version: fixed width numbers
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
is there an easy way to output numbers in a simple print() call in a fixed width? for cases with leading zeros i have been doing:
print(str(number+1000000)[1:])
but now i want to have leading spaces. do i need to write a function to do this?
fstring:
>>> zz = 45678
>>> yy = 345
>>> print(f'{zz:10}{yy:10}')
     45678       345
How are you getting leading zeroes anyway?

For leading spaces you can use either append to your string or make use of more than one argument to your print function.

print( 1*' ' + str(number+1000000)[1:] )
i am getting leading zeroes by adding a big enough power of 10 and slicing off the leading '1'. i suppose this might work:
print((width*' '+str(number))[-width:])
(May-26-2019, 05:41 AM)Nwb Wrote: [ -> ]How are you getting leading zeroes anyway?

There is string method .zfill for this:

>>> help(str.zfill)
zfill(self, width, /)
    Pad a numeric string with zeros on the left, to fill a field of the given width.
    
    The string is never truncated.
(END)
>>> str(42).zfill(5)
'00042'
Ah okay so you want to add leading zeroes.

You can use string formatting to do this very easily.
print(f'{number:0(length)}')

eg:
>>> print(f'{10:020}')
00000000000000000010
(May-26-2019, 01:13 AM)Skaperen Wrote: [ -> ]is there an easy way to output numbers in a simple print() call in a fixed width?

I don't know whether it qualifies as 'easy way', but there is str.rjust (also str.ljust)

>>> help(str.rjust)
Help on method_descriptor:

rjust(self, width, fillchar=' ', /)
    Return a right-justified string of length width.
    
    Padding is done using the specified fill character (default is a space).
(END)
>>> '42'.rjust(5)
'   42'
>>> '42'.rjust(5,'*')
'***42'
(May-26-2019, 08:16 AM)Nwb Wrote: [ -> ]Ah okay so you want to add leading zeroes.

You can use string formatting to do this very easily.
print(f'{number:0(length)}')

eg:
>>> print(f'{10:020}')
00000000000000000010
read my first post. i have been doing leading zeroes. now i want to do leading spaces.
Yeah I misread. See what Larz60+ wrote. That's the best way to do it.
i have a couple ways to do it, now.
Pages: 1 2