python equivalent for fputc

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Wed Aug 30 21:28:27 EDT 2006


Putty wrote:
> I'm porting a program a friend wrote in C over to Python and I've run
> into a little hang-up.  The C program writes characters out to a file.
> I'm 99% sure that a conversion is going on here as well.  I know for a
> fact that it's taking a number and turning it into a character.
> So what kind of call can I make to do it in Python?

There may be some ways. Here is the data:
from random import randint
vals = [randint(0, 255) for i in xrange(10)]

This is probably the most common way:
print "".join(chr(c) for c in vals)

If you need to access the chars one after the other, this may be a
(quite slower, but less memory consuming) alternative:

import sys
write = sys.stdout.write
for c in vals:
    write(chr(c))
print

In some cases a solution like this one can be useful too:

import array
print array.array("B", vals).tostring()

Bye,
bearophile




More information about the Python-list mailing list