簡短的回答,你必須自己實現它,如果你想保持這種格式輸出:
#!/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)
其產生預期的
['éléphant', 'Hello World']
但是,請注意,它會將所有元素放在引號內(例如偶數),因此如果您期望列表中的字符串以外的任何內容,則可能需要更復雜的實現。
再回應
的問題是Python的運行罩下str(my_list)
,在打印之前。然後,在列表的每個元素上依次運行repr()
。現在
,repr()
一個字符串返回字符串的ASCII唯一代表。也就是說,你看到的'\ xc3'是一個實際的反斜槓,一個實際的'c'和一個實際的'3'字符。
無法解決,如問題上的list.__str__()
實施。
下面示例程序來證明。
#!/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"))
產生這樣的:
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']
你可以做這樣的事情以正確編碼您'print'聲明:'>>>印刷再版(my_list).decode( 「Unicode的逃逸」) .encode('latin-1')' 我發佈了這個答案,但刪除了它,因爲我只在python2中測試過,所以我現在評論。 –
@ViníciusAguiar我的確在使用python2。如果用'utf-8'替換'latin-1' – fonfonx
,那麼你的回答就很好。哦,那很好!我不會取消刪除它,因爲它看起來已經有幾個很好的答案了。謝謝你讓我知道! =) –