V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
vtoexsir
V2EX  ›  Python

python 怎么判断一个字符是否为全角还是半角?

  •  
  •   vtoexsir · 2016-12-11 09:24:38 +08:00 · 5714 次点击
    这是一个创建于 2692 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如题, 怎么判断一个字符是否为全角还是半角? 多谢您的回复!

    8 条回复    2020-07-03 23:20:51 +08:00
    fy
        1
    fy  
       2016-12-11 09:29:12 +08:00 via Android
    ord 一下 看是不是在 255 以下?
    veelog
        2
    veelog  
       2016-12-11 09:37:29 +08:00 via Android
    判断字符宽度
    Khlieb
        3
    Khlieb  
       2016-12-11 09:45:58 +08:00 via Android
    按编码
    crab
        4
    crab  
       2016-12-11 10:04:21 +08:00
    ASCII 大于 128
    staticor
        5
    staticor  
       2016-12-12 11:19:30 +08:00
    参考 http://stackoverflow.com/questions/10959227/how-to-distinguish-whether-a-word-is-half-width-or-full-width

    半角字符使用 ord 返回对应的值, 全角字符使用 ord 会报异常.

    也可以使用 unicode 值判断
    vtoexsir
        6
    vtoexsir  
    OP
       2016-12-12 18:50:38 +08:00
    转为 gb18030 编码,然后查看长度,等于 2 的就是全角,等于 1 的就是半角,这也是全角半角的本意吧
    type
        7
    type  
       2016-12-13 17:25:53 +08:00
    使用 len() 方法,返回字符长度,长度为 1 的是半角,长度为 2 为全角。

    不知这样是否可行?
    m3ng9i
        8
    m3ng9i  
       2020-07-03 23:20:51 +08:00   ❤️ 1
    import unicodedata

    unicodedata.east_asian_width('我') # W (宽)
    unicodedata.east_asian_width('i') # Na (窄)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5199 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 09:24 · PVG 17:24 · LAX 02:24 · JFK 05:24
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.