【问题标题】:The 'isalnum' method doesn't work properly in the code [duplicate]'isalnum' 方法在代码中无法正常工作 [重复]
【发布时间】:2022-01-13 03:31:07
【问题描述】:

我刚开始学习 Python 几天,这是一个愚蠢的问题。我认为这段代码应该返回false,因为输入字符不是字母,但我不明白为什么它会返回true。如何设置以确保此方法正常工作。 ``

word='½Ã'
if word.isalnum():
    print("it's true")
else:
    print("it's not alpha")

``

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    根据 Unicode 标准,其中一个字符是 numeric,其中一个是 alpha,因此对于 .isalnum(),整个字符串返回 True

    In [1]: word='½Ã'
    
    In [2]: [w.isalpha() for w in word]
    Out[2]: [False, True]
    
    In [3]: [w.isnumeric() for w in word]
    Out[3]: [True, False]
    

    上面链接的 python 文档中描述了每种方法返回 True 的字符的定义。

    如果您尝试测试字符串是否仅包含 ASCII 字符而不包含 unicode,则可以使用.isacii() 方法:

    In [4]: [w.isascii() for w in word]
    Out[4]: [False, False]
    

    【讨论】:

    • 感谢您的详细解释。我想我只是对这种方法有错误的印象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    相关资源
    最近更新 更多