Kurze Antwort, Sie haben es selbst zu implementieren, wenn Sie die Ausgabe in diesem Format behalten möchten:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
my_list = ['éléphant', 'Hello World']
def print_list (l):
print ("[" + ", ".join(["'%s'" % str(x) for x in l]) + "]")
print_list (my_list)
Welche erzeugt die erwarteten
['éléphant', 'Hello World']
Beachten Sie jedoch, dass es alle Elemente in Anführungszeichen setzen würde (auch Zahlen, zum Beispiel), so können Sie eine komplexere Implementierung benötigen, wenn Sie etwas anderes als Zeichenfolge auf Ihrer Liste erwarten ist.
Längere Antwort
Das Problem ist, dass Python läuft str(my_list)
unter den Hauben, bevor es gedruckt wird. Und das wiederum läuft repr()
auf jedem der Elemente der Liste.
Jetzt gibt repr()
für einen String eine ASCII-Darstellung des Strings zurück. Das heißt, diese '\ xc3', die Sie sehen, sind ein tatsächlicher Backslash, ein tatsächliches 'c' und ein tatsächliches '3' Zeichen.
Sie können nicht das umgehen, wie das Problem bei der Umsetzung von list.__str__()
ist.
Unten ein Beispielprogramm, dass zu demonstrieren.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vi: ai sts=4 sw=4 et
import pprint
my_list = ['éléphant', 'Hello World']
# under the hood, python first runs str(my_list), before printing it
my_list_as_string = str(my_list)
# str() on a list runs repr() on each of the elements.
# However, it seems that __repr__ on a string transforms it to an
# ASCII-only representation
print ('str(my_list) = %s' % str(my_list))
for c in my_list_as_string:
print c
print ('len(str(my_list)) = %s' % len(str(my_list)))
print ("\n")
# Which we can confirm here, where we can see that it it also adds the quotes:
print ('repr("é") == %s' % repr("é"))
for c in repr("é"):
print c
print ('len(repr("é")) == %s' % len(repr("é")))
print ("\n")
# Even pprint fails
print ("pprint gives the same results")
pprint.pprint(my_list)
# It's useless to try to encode it, since all data is ASCII
print "Trying to encode"
print (my_list_as_string.encode ("utf8"))
Welche dies erzeugt:
so etwas wie dies richtig
str(my_list) = ['\xc3\xa9l\xc3\xa9phant', 'Hello World']
[
'
\
x
c
3
\
x
a
9
l
\
x
c
3
\
x
a
9
p
h
a
n
t
'
,
'
H
e
l
l
o
W
o
r
l
d
'
]
len(str(my_list)) = 41
repr("é") == '\xc3\xa9'
'
\
x
c
3
\
x
a
9
'
len(repr("é")) == 10
pprint gives the same results
['\xc3\xa9l\xc3\xa9phant', 'Hello World']
Trying to encode
['\xc3\xa9l\xc3\xa9phant', 'Hello World']
Sie tun können, um Ihre 'print' Anweisung zu codieren:' >>> print repr (my_list) .decode ("Unicode-Escape") .encode ('latin-1') ' Ich habe dies als Antwort gepostet, aber gelöscht, da ich das nur in python2 getestet habe, daher kommentiere ich jetzt. –
@ ViníciusAguiar Ich habe tatsächlich python2 verwendet. Ihre Antwort funktioniert gut, wenn Sie 'latin-1' durch 'utf-8' ersetzen – fonfonx
Oh, das ist gut! Ich werde es nicht wiederherstellen, da es aussieht, als gäbe es schon ein paar gute Antworten. Danke, dass du mich darüber informiert hast! =) –