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
如果要检查变量
x
的类型,可以使用以下命令:在python中,String和Char将具有相同的类型和相同的输出,这与java等语言不同。在
^{pr2}$编辑:
正如@Kay建议的那样,您应该使用
isinstance(foo, Bar)
而不是type(foo) is bar
,因为isinstance正在检查继承,而类型没有检查继承。在有关
isinstance
与type
的更多详细信息,请参见this使用isinstance还将支持unicode字符串。在
编辑2:
使用正则表达式仅验证一个字母
结果答案是
not((x>='A' and x<='Z') or (x>='a' and x<='z'))
相关问题 更多 >
编程相关推荐