当且仅当x不是真时,写一个值为真的表达式

2024-10-11 16:25:10 发布

您现在位置:Python中文网/ 问答频道 /正文

假设x是一个已给定值的字符串变量。当且仅当x不是字母时,编写一个值为true的表达式。在


Tags: 字符串true表达式字母
3条回答
def isLetter(ch):
    import string
    return len(ch) == 1 and ch in string.ascii_letters


print(isLetter('A'))
True

如果要检查变量x的类型,可以使用以下命令:

if type(x) is str:
    print 'is a string'

在python中,String和Char将具有相同的类型和相同的输出,这与java等语言不同。在

^{pr2}$

编辑:

正如@Kay建议的那样,您应该使用isinstance(foo, Bar)而不是type(foo) is bar,因为isinstance正在检查继承,而类型没有检查继承。在

有关isinstancetype的更多详细信息,请参见this

使用isinstance还将支持unicode字符串。在

isinstance(u"A", basestring)
>>> true

# Here is an example of why isinstance is better than type
type(u"A") is str
>>> false
type(u"A") is basestring
>>> false
type(u"A") is unicode
>>> true

编辑2:

使用正则表达式仅验证一个字母

import re

re.match("^[a-zA-Z]$", "a") is not None
>>> True

re.match("^[a-zA-Z]$", "0") is not None
>>> False

结果答案是not((x>='A' and x<='Z') or (x>='a' and x<='z'))

相关问题 更多 >

    热门问题