如何测试python发行版是否具有unicode属性

2024-09-30 20:30:12 发布

您现在位置:Python中文网/ 问答频道 /正文

在可能的情况下,我想使用unicode python字符串u"\U0001d54d",但是如果在显示它时出现问题,我只想使用一个“V”。你知道吗

在某些系统上,unicode打印。 在其他情况下,它什么也不显示(我假设发生了.encode("ascii","ignore")类型的事情),或者

UnicodeEncodeError: 'ascii' codec can't encode character u'\U0001d54d' in position 14: ordinal not in range(128)

根据功能。。。两者都不好。你知道吗

有没有一个测试,我可以做,以确定是否使用我的特殊字符?还是比这更复杂?你知道吗


Tags: 字符串in类型系统asciiunicode情况事情
3条回答

引用Python术语表

Easier to ask for forgiveness than permission:

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

Python中处理运行时错误的标准方法是try\except。try打印字符串,并except UnicodeEncodeError在出现错误时进行回退。你知道吗

>>> try:
...     s=u"\U0001d54d"
...     print s
... except UnicodeEncodeError:
...     print "V"
...

您可以轻松检查stdout支持什么编码:

>>> import sys
>>> sys.stdout.encoding
'UTF-8'

显示部分取决于要打印的位置。Python将输出编码为终端应用程序正在使用的任何编码。您可以检查环境变量以确保字符是在您需要的区域设置中定义的,例如:

import os

if os.environ.get('LC_ALL') == 'es_ES.utf8':
    # You know that 'es_ES.utf8' has your character ...

同时检查LC_CTYPE

相关问题 更多 >