相关疑难解决方法(0)

在Python中管道stdout时设置正确的编码

管道Python程序的输出时,Python解释器会对编码感到困惑,并将其设置为None.这意味着这样的程序:

# -*- coding: utf-8 -*-
print u"åäö"
Run Code Online (Sandbox Code Playgroud)

正常运行时会正常工作,但失败时:

UnicodeEncodeError:'ascii'编解码器无法对位置0中的字符u'\ xa0'进行编码:序数不在范围内(128)

当在管道序列中使用时.

在配管时使这项工作的最佳方法是什么?我可以告诉它使用shell/filesystem /无论使用什么编码吗?

到目前为止我看到的建议是直接修改你的site.py,或者使用这个hack对defaultencoding进行硬编码:

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print u"åäö"
Run Code Online (Sandbox Code Playgroud)

是否有更好的方法使管道工作?

python terminal encoding stdout python-2.x

327
推荐指数
7
解决办法
19万
查看次数

如何控制包含东亚字符的Unicode字符串的填充

我有三个UTF-8蜇伤:

hello, world
hello, ??
hello, ?rld
Run Code Online (Sandbox Code Playgroud)

我只想要前10个ascii-char-width,以便括号在一列中:

[hello, wor]
[hello, ? ]
[hello, ?r]
Run Code Online (Sandbox Code Playgroud)

在控制台中:

width('??')==width('worl')
width('? ')==width('wor')  #a white space behind '?'
Run Code Online (Sandbox Code Playgroud)

一个中文字符是三个字节,但在控制台中显示时只有2个ascii字符宽度:

>>> bytes("hello, ??", encoding='utf-8')
b'hello, \xe4\xb8\x96\xe7\x95\x8c'
Run Code Online (Sandbox Code Playgroud)

format()当UTF-8字符混入时,python 没有帮助

>>> for s in ['[{0:<{1}.{1}}]'.format(s, 10) for s in ['hello, world', 'hello, ??', 'hello, ?rld']]:
...    print(s)
...
[hello, wor]
[hello, ?? ]
[hello, ?rl]
Run Code Online (Sandbox Code Playgroud)

它不漂亮:

 -----------Songs-----------
|    1: ??                  |
|    2: ???                 |
|    3: ??????              |
|    4: ?????               |
|    5: ???(CUCURRUCUCU …
Run Code Online (Sandbox Code Playgroud)

python unicode string-formatting

7
推荐指数
3
解决办法
2986
查看次数