Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print LIST of unicode chars without escape characters

If you have a string as below, with unicode chars, you can print it, and get the unescaped version:

>>> s = "äåö"
>>> s
'\xc3\xa4\xc3\xa5\xc3\xb6'
>>> print s
äåö

but if we have a list containing the string above and print it:

>>> s = ['äåö']
>>> s
['\xc3\xa4\xc3\xa5\xc3\xb6']
>>> print s
['\xc3\xa4\xc3\xa5\xc3\xb6']

You still get escaped character sequences. How do you go about to get the content of the list unescaped, is it possible? Like this:

>>> print s
['äåö']

Also, if the strings are of the unicode type, how do you go about doing the same as above?

>>> s = u'åäö'
>>> s
u'\xe5\xe4\xf6'
>>> print s
åäö
>>> s = [u'åäö']
>>> s
[u'\xe5\xe4\xf6']
>>> print s
[u'\xe5\xe4\xf6']
like image 481
Parham Avatar asked May 28 '13 18:05

Parham


3 Answers

When you print a string, you get the output of the __str__ method of the object - in this case the string without quotes. The __str__ method of a list is different, it creates a string containing the opening and closing [] and the string produced by the __repr__ method of each object contained within. What you're seeing is the difference between __str__ and __repr__.

You can build your own string instead:

print '[' + ','.join("'" + str(x) + "'" for x in s) + ']'

This version should work on both Unicode and byte strings in Python 2:

print u'[' + u','.join(u"'" + unicode(x) + u"'" for x in s) + u']'
like image 73
Mark Ransom Avatar answered Sep 26 '22 01:09

Mark Ransom


Is this satisfactory?

>>> s = ['äåö', 'äå']
>>> print "\n".join(s)
äåö
äå
>>> print ", ".join(s)
äåö, äå


>>> s = [u'åäö']
>>> print ",".join(s)
åäö
like image 32
sberry Avatar answered Sep 23 '22 01:09

sberry


In Python 2.x the default is what you're experiencing:

>>> s = ['äåö']
>>> s
['\xc3\xa4\xc3\xa5\xc3\xb6']

In Python 3, however, it displays properly:

>>> s = ['äåö']
>>> s
['äåö']
like image 44
jathanism Avatar answered Sep 24 '22 01:09

jathanism