[Chicago] constant length string manipulation

Pete pfein at pobox.com
Thu Nov 29 22:28:34 CET 2007


On Thursday November 29 2007 4:06:57 pm Lukasz Szybalski wrote:
> Hello,
> Is there a string function in python that does the following:
> I need a string of length 5 char, and I will pass a longer and shorter
> string but I always need to get string of length 5.
> If my string is longer its easy:
> a=b[:5]
> but if it is shorter
> a=b[:5] will put empty space at the beginning. I need to to put the
> space at the end.
>
> Is there another line of code that can do that without if statements?
>
> a='%5s' % b works the same as a=[b:5]
>

In [4]: "foo".ljust(5, ' ')
Out[4]: 'foo  '

In [5]: "faaaaaaaaaaaoo".ljust(5, ' ')
Out[5]: 'faaaaaaaaaaaoo'

In [6]: "faaaaaaaaaaaoo".ljust(5, ' ')[:5]
Out[6]: 'faaaa'

-- 
Peter Fein   ||   773-575-0694   ||   pfein at pobox.com
http://www.pobox.com/~pfein/   ||   PGP: 0xCCF6AE6B
irc: pfein at freenode.net   ||   jabber: peter.fein at gmail.com


More information about the Chicago mailing list