String Formatting?

Alex Martelli alex at magenta.com
Sat Aug 26 15:38:39 EDT 2000


"William Dandreta" <wjdandreta at worldnet.att.net> wrote in message
news:aHTp5.4303$Q36.315165 at bgtnsc07-news.ops.worldnet.att.net...
> I am having a problem with string formatting.
> I am writing strings to a binary file and the results are not as expected.
> For example,
>
> 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.

The docs (2.1.5.1 in the Library Reference) mention C's sprintf, and don't
give much more details than that.

    "%30.30s" % x

will do what you want.


Alex







More information about the Python-list mailing list