String Formatting?

Erik Max Francis max at alcyone.com
Sat Aug 26 15:07:10 EDT 2000


William Dandreta wrote:

> record = '...%30s...' % (...x...)
> outputFile.write(record)
> 
> The records are fixed length and require x to be 30 bytes long. If x
> is
> longer than 30 bytes, the string formatting mechanism does not
> truncate x to
> 30 and the file is corrupted. I've been using x[:30] in place of x to
> get it
> to work.
> 
> Is this the way string formatting is supposed to work? I could find no
> info
> in the doc's.

Yep; Python inherits its string % operator from C, and in C the number
represents the width of the field, but strings longer than that length
are not truncated.  If you want to ensure that any string is truncated
to that hard limit, then use the precision field in the format
specifier:

    record = '%30.30s' % x

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Suffering is a journey which has an end.
\__/ Matthew Fox
    Alcyone Systems / http://www.alcyone.com/
 Alcyone Systems, San Jose, California.



More information about the Python-list mailing list