python - 在 Python 中检查一个字符是全角还是半角

标签 python

我想使用 Python 检查一个字符是全角还是半角

string="你好hallo"
for char in string:
    if( \uFF60- \u0f01  and \uFFE0-\uFFE6 ): print( char +"is fullwidth")
    elif(\uFF61-\uFFDC and \uFFE8-\uFFEE):print(char+ " is halfwidth")

请帮我把这段伪代码改成真正的python代码。

最佳答案

正如 Alex Thornton 提到的,使用 unicodedata.east_asian_width() 是正确的。但是,它具有以下返回值:

# East_Asian_Width (ea)

ea ; A         ; Ambiguous
ea ; F         ; Fullwidth
ea ; H         ; Halfwidth
ea ; N         ; Neutral
ea ; Na        ; Narrow
ea ; W         ; Wide

'W''F''A' 的返回值在 Windows 上应被视为全角。

引用:http://www.unicode.org/reports/tr44/tr44-4.html#Validation_of_Enumerated


在 POSIX 平台上,引号字符(u'“'u'”')被认为是有歧义,在控制台中实际上是 1 个字符宽度。对于控制台使用,您可以尝试使用第三方库 urwid :

>>> from urwid.util import str_util
>>> str_util.get_width(ord(u'x'))
1
>>> str_util.get_width(ord(u'“'))
1
>>> str_util.get_width(ord(u'你'))
2

关于python - 在 Python 中检查一个字符是全角还是半角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23058564/

相关文章:

python - reshape Pandas DataFrame : switch columns to indices and repeated values as columns

python 使用包含模式复制文件

python - 如何建立具有相互依赖关系的Python类集合?

python - 如何舍入破折号表中的小数位

python - 获取嵌套字典中唯一值的列表(或集合)

python - 将置信区间计算为分位数

python - Flask: TypeError: blog() 有一个意外的关键字参数 'user'

python - Python或Ruby我应该学习哪一个?

python - '模块'对象在django中没有属性 'models'错误

python - 如何在django rest框架中上传多个文件