From: Dan S. <drs...@gm...> - 2011-04-18 00:22:55
|
How does one, in Jython 2.5.2, convert from a byte string to a text string, and vice versa? I'd like to support Jython in my opensource python2x3 module, but Jython's string handling seems different enough from that of other Pythons that I'm not clear on how to do so. I found an article saying that if you do a binary read in Jython, you'll get a binary str that just keeps the high bytes zeroed, but I didn't notice anything about converting from one (always zero high bytes to nonzero high bytes, for EG) to the other. Python2x3's at http://stromberg.dnsalias.org/svn/python2x3/trunk - and I'm including a copy at the bottom of this message. TIA! #!/usr/bin/python '''Provides code and data to facilitate writing python code that runs on 2.x and 3.x, including pypy''' # I'm afraid pylint won't like this one... import sys import platform def python_major(result = int(platform.python_version_tuple()[0])): '''Return an integer corresponding to the major version # of the python interpreter we're running on''' return result if python_major() == 2: empty_bytes = '' null_byte = '\0' bytes_type = str def intlist_to_binary(intlist): '''Convert a list of integers to a binary string type''' return ''.join(chr(byte) for byte in intlist) def string_to_binary(string): '''Convert a text string to a binary string type''' return string def binary_to_intlist(binary): '''Convert a binary string to a list of integers''' return [ ord(character) for character in binary ] def binary_to_string(binary): '''Convert a binary string to a text string''' return binary elif python_major() == 3: empty_bytes = ''.encode('utf-8') null_byte = bytes([ 0 ]) bytes_type = bytes def intlist_to_binary(intlist): '''Convert a list of integers to a binary string type''' return bytes(intlist) def string_to_binary(string): '''Convert a text string (or binary string type) to a binary string type''' if isinstance(string, str): return string.encode('latin-1') else: return string def binary_to_intlist(binary): '''Convert a binary string to a list of integers''' return binary def binary_to_string(binary): '''Convert a binary string to a text string''' return binary.decode('latin-1') else: sys.stderr.write('%s: Python < 2 or > 3 not (yet) supported\n' % sys.argv[0]) sys.exit(1) |