[Chicago] constant length string manipulation

Carl Karsten carl at personnelware.com
Thu Nov 29 22:38:31 CET 2007


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. 

um, no it won't.

 >>> 'abc'[:5]
'abc'


> I need to to put the
> space at the end.
> 
> Is there another line of code that can do that without if statements?
> 

 >>> '%-5s'%('ab'[:5])
'ab   '
 >>> '%-5s'%('abcdef'[:5])
'abcde'

 >>> '%-*s'%(5,'abc'[:5])
'abc  '
 >>> '%-*s'%(5,'abcdef'[:5])
'abcde'

 >>> ('%s     '%'abc')[:5]
'abc  '
 >>> ('%s     '%'abcdef')[:5]
'abcde'

http://docs.python.org/lib/typesseq-strings.html

 > a='%5s' % b works the same as a=[b:5]
um, no it doesn't, even with the typo corrected.
I suggest using copy/paste when copying code.  (or anything else I guess.)
and including the output from your tests.

Carl K


More information about the Chicago mailing list