推荐学习书目
› 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 · Dec 11, 2016 · 7053 views
    This topic created in 3582 days ago, the information mentioned may be changed or developed.

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

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

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

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

    不知这样是否可行?
    m3ng9i
        8
    m3ng9i  
       Jul 3, 2020   ❤️ 1
    import unicodedata

    unicodedata.east_asian_width('我') # W (宽)
    unicodedata.east_asian_width('i') # Na (窄)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2443 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 13:58 · PVG 21:58 · LAX 06:58 · JFK 09:58
    ♥ Do have faith in what you're doing.