I want to concatenate a list of various Python objects into one string. The objects can be literally anything. I thought I could simply do this using the following code:
' '.join([str(x) for x in the_list])
but unfortunately that sometimes gives me a UnicodeEncodeError:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 80: ordinal not in range(128)
in this SO answer I found someone who says that 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 unicodes but for example int
s I get an AttributeError: 'int' object has no attribute 'encode'
. So this means I need to use some kind of if-statement to check what kind of type it is and how to convert it. But when should I use .encode('utf-8')
and when should I use str()
?
It would be even better if I could also do some kind of oneliner for this, but I wouldn't know how? Does anybody else know? All tips are welcome!