Search code examples
pythonpython-2.7utf-8non-ascii-characterspython-unicode

How to print list elements with non-ASCII characters in functional style?


I'm trying to deal with strings containing non-ASCII characters in Python 2.7. Specifically, I want to print the elements of the following list in order to display their external representation:

foo = "mädchen wörter mutter".split()

Like this:

>>> for x in foo:
...     print x
... 
mädchen
wörter
mutter

Except I need to do it in functional style. But if I try the following, without using print, it's the internal representation that is shown:

>>> [x for x in foo]
['m\xc3\xa4dchen', 'w\xc3\xb6rter', 'mutter']

I tried using print like this, but it obviously doesn't work either as this prints the whole list instead of each separate element:

>>> print [x for x in foo]
['m\xc3\xa4dchen', 'w\xc3\xb6rter', 'mutter']

And placing print inside the square brackets returns a syntax error:

>>> [print x for x in foo]
  File "<stdin>", line 1
    [print x for x in foo]
         ^
SyntaxError: invalid syntax

I then tried using a function that would print x:

>>> def show(x):
...     print(x)
... 

>>> [show(x) for x in foo]
mädchen
wörter
mutter
[None, None, None]

This almost works, except for the [None, None, None] at the end (where does that comes from?).

Is there a functional way to just output something like this:

>>> [*do_something* for x in foo]
mädchen
wörter
mutter

Thanks for your help!


Solution

  • How about using string.join(..) ?

    print "\n".join(foo)
    

    Also, note that what you are using is called: list comprehension. And typically, list comprehensions are used in a sense of map -- that is without side-effects. Calling show(..) on every elements, and discarding the result of list comprehension is not how it is supposed to be used..


    This almost works, except for the [None, None, None] at the end (where does that comes from?).

    It comes from the return value of list-comprehension. It is show(..) applied to each element, and since the function return None you see 3 Nones.