Unicode Objects in Tuples

Peter Otten __peter__ at web.de
Fri Oct 11 04:51:19 EDT 2013


Stephen Tucker wrote:

> I am using IDLE, Python 2.7.2 on Windows 7, 64-bit.
> 
> I have four questions:
> 
> 1. Why is it that
>      print unicode_object
> displays non-ASCII characters in the unicode object correctly, whereas
>      print (unicode_object, another_unicode_object)
> displays non-ASCII characters in the unicode objects as escape sequences
> (as repr() does)?
> 
> 2. Given that this is actually *deliberately *the case (which I, at the
> moment, am finding difficult to accept), what is the neatest (that is, the
> most Pythonic) way to get non-ASCII characters in unicode objects in
> tuples displayed correctly?

"correct" being a synonym for "as I expect" ;)
 
> 3. A similar thing happens when I write such objects and tuples to a file
> opened by
>      codecs.open ( ..., "utf-8")
> I have also found that, even though I use  write  to send the text to the
> file, unicode objects not in tuples get their non-ASCII characters sent to
> the file correctly, whereas, unicode objects in tuples get their
> characters sent to the file as escape sequences. Why is this the case?
> 
> 4. As for question 1 above, I ask here also: What is the neatest way to
> get round this?

I'll second Ben's recommendation of Python 3:

>>> t = "mäßig", "müßig", "nötig"
>>> print(t)
('mäßig', 'müßig', 'nötig')
>>> print(*t)
mäßig müßig nötig
>>> print(*t, sep=", ")
mäßig, müßig, nötig

All three variants also work with files. Example:

>>> with open("tmp.txt", "w") as outstream:
...     print(*t, file=outstream)
... 
>>> open("tmp.txt").read()
'mäßig müßig nötig\n'


Should you decide to stick with Python 2 you can use a helper function:

>>> t = u"mäßig", u"müßig", u"nötig"
>>> def pretty_tuple(t, sep=u", "):
...     return sep.join(map(unicode, t))
... 
>>> print pretty_tuple(t)
mäßig, müßig, nötig
>>> print pretty_tuple(t, sep=u" ")
mäßig müßig nötig





More information about the Python-list mailing list