perl style formating

Hans Nowak wurmy at earthlink.net
Sat Dec 15 09:06:35 EST 2001


Les Ander wrote:
> 
> Hi,
> i am new to python.
> 
> say i wanted to print out 3 variable in the following format:
> $name is left justified and has the width of size 10
> $comment is left justified and starts at column 11 and ends at 40
> $line starts at 41 and is of variable length)
> 
> in perl i would write it as:
> 
> format OUT =
> @<<<<<<<<<< >@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<    >@*
> $name, $comment, $line;

Cool, ASCII art on c.l.py. Is it a centipede? <wink>

As people pointed out, this can be done with string formatting:

>>> name = "Fred"
>>> comment = "And nice red uniforms."
>>> line = "Bye!"
>>> "%-10s %-30s %s" % (name, comment, line)
'Fred       And nice red uniforms.         Bye!'

However, if the strings are longer than 10 and 30 characters,
respectively, they will show up entirely, rather than being
clipped:

>>> name = "Dr. Fred Mbogo"
>>> "%-10s %-30s %s" % (name, comment, line)
'Dr. Fred Mbogo And nice red uniforms.         Bye!'

You can prevent this using a . (dot):

>>> "%-10.10s %-30.30s %s" % (name, comment, line)
'Dr. Fred M And nice red uniforms.         Bye!'

HTH,

--Hans



More information about the Python-list mailing list