print format
Dave Angel
davea at ieee.org
Tue Dec 15 06:30:10 EST 2009
Gabriel Genellina wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">En Tue,
> 15 Dec 2009 00:28:11 -0300, Dave Angel <davea at ieee.org> escribió:
>> mattia wrote:
>
>>> Hi all, I wanto to print just the first 5 characters of a string,
>>> why this doesn't work (py3.1)?
>>>
>>>>>> print("{0:5}".format("123456789"))
>>>>>>
>>> 123456789
>>> I know I could use print("123456789"[:5]), yeah it's a stupid
>>> example, but isn't format for string formatting?
>>>
>> The width field of the format is a *minimum* width. So you can use
>> it to force padding, but not truncation. If you need the string
>> truncated, just use slicing, as you already showed.
>
> Or use the .precision specifier:
>
> py> "{0:.5}".format("123412341234")
> '12341'
>
> {0:5.5} has the same effect. See
> http://docs.python.org/library/string.html#format-string-syntax
>
Whoa! i never realized you could use precision on strings. I knew
(the hard way) that it won't work on ints, but I never thought to try it
on strings.
Thanks.
DaveA
More information about the Python-list
mailing list