Easily convert unicode tuple to python string tuple???

Jeff Epler jepler at unpythonic.net
Tue Apr 20 11:36:42 EDT 2004


You can use a listcomp to do "something" to each element of an iterable:

>>> s = (u'USER', u'NODE', u'HASH', u'IDNBR')
>>> [i.encode("ascii") for i in s]
['USER', 'NODE', 'HASH', 'IDNBR']

You can use tuple(s) to turn an iterable s into a tuple:
>>> tuple(_)
('USER', 'NODE', 'HASH', 'IDNBR')

Here's a function that does both in one step, as a function:
>>> def decode_tuple(t, encoding="ascii"):
...    return tuple([i.encode(encoding) for i in t])
...
>>> decode_tuple(s)
('USER', 'NODE', 'HASH', 'IDNBR')

Jeff




More information about the Python-list mailing list