python中print无法打印在控制台输出,python 3.0,如何使print()输出unicode?

博主在使用Python3.0处理包含中文拼音的字符串时遇到编码问题,发现console输出不支持Unicode。尽管切换到Python3.0已解决部分问题,但print()函数仍无法正确显示非ASCII字符。问题在于Windows命令提示符cmd.exe无法显示特定Unicode字符。解决方案是使用支持Unicode显示的工具,如IDLE或Cygwin。
摘要由CSDN通过智能技术生成

I'm working in WinXP 5.1.2600, writing a Python application involving Chinese pinyin, which has involved me in endless Unicode problems. Switching to Python 3.0 has solved many of them. But the print() function for console output is not Unicode-aware for some odd reason. Here's a teeny program.

print('sys.stdout encoding is "' + sys.stdout.encoding + '"')

str1 = 'lüelā'

print(str1)

Output is (changing angle brackets to square brackets for readability):

sys.stdout encoding is "cp1252"

Traceback (most recent call last):

File "TestPrintEncoding.py", line 22, in [module]

print(str1)

File "C:\Python30\lib\io.py", line 1491, in write

b = encoder.encode(s)

File "C:\Python30\lib\encodings\cp1252.py", line 19, in encode

return codecs.charmap_encode(input,self.errors,encoding_table)[0]

UnicodeEncodeError: 'charmap' codec can't encode character '\u0101'

in position 4: character maps to [undefined]

Note that ü = \xfc = 252 gives no problem since it's upper ASCII. But ā = \u0101 is beyond 8-bits.

Anyone have an idea how to change the encoding of sys.stdout to 'utf-8'? Bear in mind that Python 3.0 no longer uses the codecs module, if I understand the documentation right.

Apologies, I gave you the program without the preamble. Before the 3 lines given, it starts like this:

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import sys

Unfortunately, the coding specified by the "coding:" line is the coding of the source code, not of the console output. But thank you for your thoughts!

解决方案

The Windows command prompt (cmd.exe) cannot display the Unicode characters you are using, even though Python is handling it in a correct manner internally. You need to use IDLE, Cygwin, or another program that can display Unicode correctly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值