How to convert * any * Python object to string?

I want to combine a list of different Python objects into one line. Objects can be literally any. I thought I could just do this using the following code:

' '.join([str(x) for x in the_list]) 

but unfortunately this sometimes gives me a UnicodeEncodeError:

 UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 80: ordinal not in range(128) 

in this answer SO> I found a person who says I need to use .encode('utf-8') , so I changed my code to this:

 ' '.join([x.encode('utf-8') for x in the_list]) 

But if the objects are not strings or Unicode, but for example int , I get AttributeError: 'int' object has no attribute 'encode' . So this means that I need to use some kind of if statement to check what type it is and how to convert it. But when should I use .encode('utf-8') and when should str() be used?

It would be even better if I could do some kind of synth for this, but I would not know how to do this? Does anyone else know? All tips are welcome!

+6
source share
3 answers

Python 2.x uses repr() . Python 3.x uses repr() if you don't mind Unicode Unicode as a result, or ascii() if you do:

 >>> a=1 # integer >>> class X: pass ... >>> x=X() # class >>> y='\u5000' # Unicode string >>> z=b'\xa0' # non-ASCII byte string >>> ' '.join(ascii(i) for i in (a,x,y,z)) "1 <__main__.X object at 0x0000000002974B38> '\\u5000' b'\\xa0'" 

An example of the differences between 2.X and 3.X repr() and 3.X ascii() :

 >>> # Python 3 >>> s = 'pingüino' # Unicode string >>> s 'pingüino' >>> repr(s) "'pingüino'" >>> print(repr(s)) 'pingüino' >>> ascii(s) "'ping\\xfcino'" >>> print(ascii(s)) 'ping\xfcino' >>> # Python 2 >>> s = u'pingüino' >>> s u'ping\xfcino' >>> repr(s) "u'ping\\xfcino'" >>> print(repr(s)) u'ping\xfcino' 
+6
source

Instead, you can try join ing with a unicode object.

 u' '.join(unicode(x) for x in thelist) 

Or what you had before this works fine in python3. Just make sure:

  • early decoding
  • unicode everywhere
  • encode late

See this talk for more details.

+1
source

You can try combining the ternary operator with your current one-liner. In addition, join works fine with the generator, so I don't think you need to create a list. Sort of

 ' '.join(x.encode('utf-8') if isinstance(x, basestring) else str(x) for x in the_list) 
0
source

All Articles