chr / ord

S

Sean McIlroy

hello

how do i say "chr" and "ord" in the new python? the functions below
(which work in 2.6.6) show what i'm trying to do. thanks if you can
help.

def readbytes(filepath):
return [ord(x) for x in open(filepath,'rb').read()]

def writebytes(numbers,filepath):
open(filepath,'wb').write(''.join([chr(x) for x in numbers]))
 
B

Benjamin Kaplan

hello

how do i say "chr" and "ord" in the new python? the functions below
(which work in 2.6.6) show what i'm trying to do. thanks if you can
help.

def readbytes(filepath):
   return [ord(x) for x in open(filepath,'rb').read()]
Ord should still work the way you expect.
def writebytes(numbers,filepath):
   open(filepath,'wb').write(''.join([chr(x) for x in numbers]))

I haven't played around with python 3 that much, but I believe that
the bytes constructor can take an iterable of ints. So you should be
able to do
open(filepath,'wb').write(bytes(numbers))
 
S

Steven D'Aprano

hello

how do i say "chr" and "ord" in the new python?

"chr" and "ord".


the functions below (which work in 2.6.6)

Can I borrow your time machine, there's some lottery numbers I want to
get.

There is no Python 2.6.6. The latest version of 2.6 is 2.6.4.

show what i'm trying to do. thanks if you can help.

def readbytes(filepath):
return [ord(x) for x in open(filepath,'rb').read()]

def writebytes(numbers,filepath):
open(filepath,'wb').write(''.join([chr(x) for x in numbers]))


Have you tried them in "the new Python" (whatever that is...)? What do
they do that isn't what you expect?
 
S

Sean McIlroy

thanks. that did the trick. in case anyone else is in the same boat as
myself, here are the relevant correspondences:

string <-> [int] bytes <-> [int]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top