Convert variable types into unicode string
encoding, int, python, unicode, utf-8
Solution
Encoding would never result in a `unicode` object. You decode from bytes to `unicode`.
As such, you'd convert to `str` (a byte string) then to `unicode` by decoding:
str(obj).decode('utf8')
This will still fail for objects that are already `unicode` values, so you may want to use `try..except` to catch that case:
try:
obj = str(obj).decode('utf8')
except UnicodeEncodeError:
# already unicode
pass
If you try to encode a byte-string, Python 2 implicitly first decodes to `unicode` for you, which is why you got your `UnicodeDecodeError`.
Problem
I'm looking for a way to convert a variable (which could be an ASCII string, unicode string WITH extra characters like é or £, or a floats or integer) into a unicode string. `variable.encode('utf-8')` where `variable` is an integer results in `AttributeError: 'int' object has no attribute 'encode'` `str(variable).encode('utf-8')` where `variable` is the string `'£'` results in `UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 0: ordinal not in range(128)` Is there an easy way to do what I'm looking for in Python 2.7? Or do I have to check the type of variable and process it differently?