小编big*_*tle的帖子

python 3.0,如何使print()输出unicode?

我正在使用WinXP 5.1.2600,编写一个涉及中文拼音的Python应用程序,这让我遇到了无数的Unicode问题.切换到Python 3.0已经解决了许多问题.但是由于一些奇怪的原因,控制台输出的print()函数不支持Unicode.这是一个很小的计划.

print('sys.stdout encoding is "' + sys.stdout.encoding + '"')
str1 = 'lüel?'
print(str1)
Run Code Online (Sandbox Code Playgroud)

输出为(为了便于阅读,将尖括号更改为方括号):

    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]

请注意,ü=\xfc = 252没有问题,因为它是高位ASCII.但是ā=\u0101超过了8位.

任何人都知道如何将sys.stdout的编码更改为'utf-8'?请记住codecs,如果我理解文档正确,Python 3.0不再使用该模块.


道歉,我给你的程序没有序言.在给出3行之前,它开始如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys …
Run Code Online (Sandbox Code Playgroud)

printing unicode console stdout python-3.x

18
推荐指数
2
解决办法
2万
查看次数

Python:循环连续的字符?

在Python(特别是Python 3.0,但我认为不重要)中,如何在具有连续字符代码的字符序列上轻松编写循环?我想做像这样的伪代码:

for Ch from 'a' to 'z' inclusive: #
    f(Ch)
Run Code Online (Sandbox Code Playgroud)

示例:以下是一个不错的"pythonic"版本怎么样?

def Pangram(Str):
    ''' Returns True if Str contains the whole alphabet, else False '''
    for Ch from 'a' to 'z' inclusive: #
        M[Ch] = False
    for J in range(len(Str)):
        Ch = lower(Str[J])
        if 'a' <= Ch <= 'z':
            M[Ch] = True
    return reduce(and, M['a'] to M['z'] inclusive) #
Run Code Online (Sandbox Code Playgroud)

标记为#的行是伪代码.当然reduce()是真正的Python!

亲爱的巫师(特别是古老的灰胡子巫师),也许你可以说我最喜欢的语言曾经是帕斯卡.

python algorithm character python-3.x

10
推荐指数
3
解决办法
3万
查看次数

标签 统计

python-3.x ×2

algorithm ×1

character ×1

console ×1

printing ×1

python ×1

stdout ×1

unicode ×1