Hi All

Please some one Help me find out why this code doesn't work:

codes=['zlib', 'zip', 'base64', 'hex', 'utf-8']

def encoder(str, i):
    return str.encode(codes[i])

def decoder(str, i):
    return str.decode(codes[i])

en = encoder('Some string here', 2)
print en

Dani AI

Generated

A few clarifications and a safe pattern to let the user pick exactly one encoding.

As observed, the original behaviour came from applying every codec in a loop; demonstrated that. was right to point toward the codecs machinery. Two important points that caused confusion here: (1) some names like utf-8 are character encodings, while base64, hex, zlib, zip are byte-transform codecs (they turn bytes into other bytes or ASCII). They are not interchangeable and you must decode with the same codec you used to encode; (2) minimal Python installs (mobile/Py2.2) may not expose every codec, so a runtime check and fallbacks are useful.

A concise, safe approach:

  • keep a small allowed list the program accepts (by name or by index),
  • validate the choice with codecs.lookup and handle LookupError,
  • provide fallbacks using base64 / binascii if a transform codec is missing.

Example pattern:

import codecs
import base64
import binascii

ALLOWED = ['utf-8', 'base64', 'hex', 'zlib', 'zip']

def safe_encode(s, choice):
    # choice can be an index (int/long) or a codec name
    if isinstance(choice, (int, long)):
        name = ALLOWED[choice]
    else:
        name = str(choice)
    if name not in ALLOWED:
        raise ValueError("not allowed")
    try:
        codecs.lookup(name)
    except LookupError:
        if name == 'base64':
            return base64.b64encode(s)
        if name == 'hex':
            return binascii.hexlify(s)
        raise
    return s.encode(name)

Troubleshooting tips:

  • If LookupError occurs, check Python version and available encodings; use codecs.lookup to probe at runtime.
  • Remember: for reversible operations, decode with the same codec you used to encode.
  • On Python 3 the API differs: str.encode returns bytes and bytes.decode is used to get text back.

Further reading on the codecs API and common transform modules is in the official docs: codecs module documentation and base64/binascii.

Recommended Answers

All 6 Replies

It works for me and python 2.6

codes=['zlib', 'zip', 'base64', 'hex', 'utf-8']

def encoder(str, i):
    return str.encode(codes[i])

def decoder(str, i):
    return str.decode(codes[i])

thing = 'Some string here'
for i, k in enumerate(codes):
    en = encoder(thing, i)
    assert thing == decoder(en, i)
    
print "success"

Thanks Gribouillis,
Now it works, but it en/decodes the string in all encodings.
I want to select the encoding freely, for example, something like this:

en1 = encoder('String One', 2)# for base64
en2 = encoder('String Two', 3)# for hex
#en3 = ....
#and so on

Thanks Gribouillis,
Now it works, but it en/decodes the string in all encodings.
I want to select the encoding freely, for example, something like this:

en1 = encoder('String One', 2)# for base64
en2 = encoder('String Two', 3)# for hex
#en3 = ....
#and so on

I don't understand, doesn't it work as expected ? Please describe the expected output of your program and, if it "doesn't work", why it doesn't produce the expected output, or if it raises an exception, which exception ?

Do not reinvent the wheel, use codecs module: (non-unicode stuff is at the end part of the post)

Thanks again for your reply

as I said the code works, without exceptions.

it gets the value of "thing" and encodes it to all encodings at once.
its ok, but, I want the User select which encoding he needs the string to be encoded. sorry if i cant be more clear(because of language barrier, Im not an English speaker).

in other word:
i want to input encoding selectively:
Input 1: the string I want to Encode or decode
Input 2: one or two of the encodings in list "codes"

Output: Printing out the Encoded/Decoded String

@pyTony: I want to doing this in my mobile python(compatible with Python 2.2), and it has not all of the libraries

Sorry for my bad English

Thank you both.
problem solved by tweaking the code u gave to me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.