String formatting with fixed width
Jon Clements
joncle at googlemail.com
Fri Mar 16 09:34:15 EDT 2007
On 16 Mar, 13:20, Alexander Eisenhuth <newsu... at stacom-software.de>
wrote:
> Hello alltogether,
>
> is it possible to format stings with fixed width of let's say 7 character. T
> need a floating point with 3 chars before dot, padded with ' ' and 3 chars after
> dot, padded with '0'.
>
> Followingh is my approach
> >>> f = 21.1
> >>> s = "%.03f" % f
> >>> s
> '21.100'
>
> But there are missing ' '. How can I get that? (For bigger numbers than 999 they
> might be cut: 1021 -> 021)
You can use something like this:
>> print '%7.03f' % 21.1
' 21.100'
However, this will only make the string at *least* 7 long. If the
length of the number exceeds this, you'll end up with it even longer;
for instance:
>> print '%7.03f' % 2123123121.1
'2123123121.100'
>From your example about 'cutting' it, it looks like you just might be
able to take the last 7 chars from it using [-7:]
hth
Jon.
More information about the Python-list
mailing list