Anup Anup - 27 days ago 9
Ruby Question

python equivalent of ruby's ASCII-8BIT encoding scheme

I need to encoding something in ASCII-8BIT because it's part of the specification of the program.

The demo code is written in ruby and they have used

Encoding::BINARY

which is equivalent to
ASCII-8BIT


Below is the encoding aliases of ruby

Encoding.aliases
#=> {"BINARY"=>"ASCII-8BIT", "ASCII"=>"US-ASCII", "ANSI_X3.4-1986"=>"US-ASCII",
"SJIS"=>"Shift_JIS", "eucJP"=>"EUC-JP", "CP932"=>"Windows-31J"}


I need something in python for the ASCII-8BIT. The default ASCII has 0-255 i.e total 8 bits, but im not sure if thats what i need to do.

will
"str".encode("ASCII")
suffice ?

Answer

The Python equivalent is Latin-1; all Unicode codepoints from 0x00 through to 0xFF are mapped one-on-one to bytes with the same value.

Note that this would encode Unicode to a bytestring. In Python 2.7, str is already a bytestring and doesn't need encoding.