Python 写一个表达式,当且仅当x不是字母时,其值为true
假设Python 写一个表达式,当且仅当x不是字母时,其值为true,python,Python,假设x是一个给定值的字符串变量。当且仅当x不是字母时,编写一个值为true的表达式。使用正则表达式。是一个很好的学习场所,这里有官方文件: 不过,类似的方法应该可以奏效: 如果x!='[a-zA-Z]:如果要检查变量x的类型,可以使用以下命令: if type(x) is str: print 'is a string' 在python中,字符串和字符将具有相同的类型和相同的输出,这与java等语言不同 type(chr(65)) == str type('A') == str 编辑
x
是一个给定值的字符串变量。当且仅当x
不是字母时,编写一个值为true
的表达式。使用正则表达式。是一个很好的学习场所,这里有官方文件:
不过,类似的方法应该可以奏效:
如果x!='[a-zA-Z]:
如果要检查变量x
的类型,可以使用以下命令:
if type(x) is str:
print 'is a string'
在python中,字符串和字符将具有相同的类型和相同的输出,这与java等语言不同
type(chr(65)) == str
type('A') == str
编辑:
正如@Kay所建议的,您应该使用isinstance(foo,Bar)
而不是type(foo)is Bar
,因为isinstance正在检查继承,而type没有
有关isinstance
vstype
使用iInstance还将支持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
答案是
不是((x>='A'和x='A'和x='A'你的尝试是什么样子的?我最近尝试了notx.true(),它说:⇒ 意外标识符:notx,true更多提示:⇒ 您几乎可以肯定应该使用:not⇒ 几乎可以肯定,您应该使用:xx!='a'
测试x
是否不是a.x!='a'和x!='b'
测试它是否既不是“a”也不是“b”…这应该是您的第一次尝试。然后,您可以在
操作符和/或比较中了解。然后,您可能会偏离正确的路径,学习正则表达式。Th谢谢大家的帮助这不是Perl。还有数字!=字母。不要做type(foo)是Bar
。使用isinstance(foo,Bar)实际上Python允许你像数学符号一样编写比较:a
a
,但是a
,b
和c
只计算一次。谢谢你告诉我。我将不得不尝试一下,不需要太复杂返回而不是x.isalpha()
,如果不是字母,就不能是字母写一个值为真的表达式当且仅当x不是字母时,这是最迂回的方法。
def isLetter(ch):
import string
return len(ch) == 1 and ch in string.ascii_letters
print(isLetter('A'))
True