在小程序(python3)中测试字符串没有特定特征

2024-04-19 15:51:25 发布

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

我正在尝试编写一个程序,要求用户输入一个以句点结尾的全大写字符串。当输入不符合标准时,让它返回响应。我知道如何检查它是否有大写这样的特征,但是我不知道如何检查它是否没有特征。这是我尝试使用的!=(如中所示,如果字符串不=大写),但它不起作用。谢谢你的意见,我是新来的,如果这是个愚蠢的问题,我很抱歉。你知道吗

 """Making sure they use uppercase and end with a period"""

s = input("Please enter an upper-case string ending with a period: ")

if s.isupper() and s.endswith("."):
     print("Input meets both requirements.") 
elif s!=upper():
     print ("Input is not all upper case.")
elif s!=endswith("."):
    print ("Input does not end with a period.")
else :
     print ("You just don't want to do this, do you?")

Tags: and字符串inputwithnot特征upperdo
3条回答

只是对代码做了一些调整。你知道吗

s = raw_input("Please enter an upper-case string ending with a period: ")

if s.isupper() and s.endswith('.'):
    print("Input meets both requirements.") 
elif not s.isupper():
     print ("Input is not all upper case.")
elif not s.endswith("."):
    print ("Input does not end with a period.")
else :
     print ("You just don't want to do this, do you?")

检查是否以“.”结尾或非大写时,不应使用!=此处为运算符。因为,这两个方法isupper()和endswith()都返回布尔值。因此要检查它是否为真,只需使用not运算符。你知道吗

使用not将反转逻辑语句

not True>;False

not False>;True

代码如下:

"""Making sure they use uppercase and end with a period"""

s = input("Please enter an upper-case string ending with a period: ")

if s.isupper() and s.endswith("."):
     print("Input meets both requirements.") 
elif not s.isupper():  #not False -> True
     print ("Input is not all upper case.")
elif not s.endswith("."): #not False -> True
    print ("Input does not end with a period.")
else :
     print ("You just don't want to do this, do you?")

你不想检查它是否不等于大写字母,因为“大写字母”是一个抽象概念,不能等于任何特定的字符串。您要检查isupper()是否为true。只要做elif not s.upper()然后elif not s.endswith(".")。你知道吗

相关问题 更多 >