推荐学习书目
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
songdg
V2EX  ›  Python

判断是否字母的问题

  •  
  •   songdg · Aug 30, 2020 · 3051 views
    This topic created in 2112 days ago, the information mentioned may be changed or developed.
    网上找的一个函数,为什么不能判断大写字母
    def is_alphabet(uchar):
    """判断一个 unicode 是否是英文字母"""
    if (uchar >= u'\u0041' and uchar<=u'\u005A') or (uchar >= u'\u0061' and uchar<=u'\u007A'):
    return True
    else:
    return False
    9 replies    2020-09-12 07:03:07 +08:00
    imn1
        1
    imn1  
       Aug 30, 2020
    什么意思?
    is_alphabet('A') 返回 False 么?
    skinny
        2
    skinny  
       Aug 30, 2020
    Python 没有 char 类型
    skinny
        3
    skinny  
       Aug 30, 2020
    你一定要按这个函数的样子写,你用 chr 函数把单个字符转换成 int
    baobao1270
        4
    baobao1270  
       Aug 30, 2020
    (uchar >= u'\u0041' and uchar<=u'\u005A') 是 ASCII 大写字母 A-Z
    (uchar >= u'\u0061' and uchar<=u'\u007A') 是 ASCII 小写字母 a-z
    注释都说了,这个智能判断是否为字母,而不能判断是大写还是小写……
    你这个写法也不够 Pythonic,可以写成
    (u'\u0041' <= uchar <=u'\u005A') or (u'\u0061' <= uchar <=u'\u007A')

    @skinny
    Python 是可以直接比较字符串的 ASCII 值的

    可以尝试以下代码:
    from enum import Enum

    class InAlphabetResult(Enum):
    UpperCase = 1
    LowerCase = 2
    NotInAlphabet = 3

    def in_alphabet(char):
    if "a" <= char <= "z":
    return InAlphabetResult.LowerCase
    if "A" <= char <= "Z":
    return InAlphabetResult.UpperCase
    return InAlphabetResult.NotInAlphabet
    baobao1270
        5
    baobao1270  
       Aug 30, 2020   ❤️ 1
    缩进没了,我贴个链接吧
    https://pastebin.ubuntu.com/p/MGZqgWGCSr/
    songdg
        6
    songdg  
    OP
       Aug 31, 2020
    @baobao1270 谢谢帮忙。
    laike9m
        7
    laike9m  
       Aug 31, 2020   ❤️ 1
    你这完全没必要啊,直接标准库 isupper 函数就完了的事

    https://docs.python.org/3.8/library/stdtypes.html#str.isupper
    songdg
        8
    songdg  
    OP
       Sep 2, 2020
    @laike9m 对,用标准库更方便。
    biglazycat
        9
    biglazycat  
       Sep 12, 2020
    def in_alphabet(char):
    char = str(char)
    if char.islower():
    return 'LowerCase'
    elif char.isupper():
    return 'UpperCase'
    else:
    return 'NotInAlphabet'

    print(in_alphabet('a'))
    print(in_alphabet('A'))
    print(in_alphabet(1))

    写的很粗糙,目前的理解就写样了。请多多指教。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3052 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 78ms · UTC 08:59 · PVG 16:59 · LAX 01:59 · JFK 04:59
    ♥ Do have faith in what you're doing.