How to print a container object using values ​​containing unicode?

Following code

# -*- coding: utf-8 -*- x = (u'abc/αβγ',) print x print x[0] print unicode(x).encode('utf-8') print x[0].encode('utf-8') 

... produces:

 (u'abc/\u03b1\u03b2\u03b3',) abc/αβγ (u'abc/\u03b1\u03b2\u03b3',) abc/αβγ 

Is there a way to get Python to print

 ('abc/αβγ',) 

which does not require me a string representation of the tuple itself? (By this I mean the union between "(" , "'" , the encoded value, "'" , "," and ")" ?

By the way, I am using Python 2.7.1.

Thanks!

+4
source share
3 answers

You can decode the str representation of your tuple with 'raw_unicode_escape' .

 In [25]: print str(x).decode('raw_unicode_escape') (u'abc/αβγ',) 
+3
source

I don’t think so - the __repr__() tuple is built-in, and AFAIK will just call __repr__ for each element of the tuple. In the case of unicode characters, you will get escape sequences.

(If the Gandaro solution does not work for you - I could not get it to work in a simple python shell, but it could be either my locale settings or something special in ipython.)

+1
source

The following should be a good start:

 >>> x = (u'abc/αβγ',) >>> S = type('S', (unicode,), {'__repr__': lambda s: s.encode('utf-8')}) >>> tuple(map(S, x)) (abc/αβγ,) 

The idea is to create a unicode subclass that has __repr__() more to your liking.

Still trying to figure out how best to surround the result with quotes, this works for your example:

 >>> S = type('S', (unicode,), {'__repr__': lambda s: "'%s'" % s.encode('utf-8')}) >>> tuple(map(S, x)) ('abc/αβγ',) 

... but it will look odd if there is a single quote in the string:

 >>> S("test'data") 'test'data' 
+1
source

Source: https://habr.com/ru/post/1391541/


All Articles