如果用户输入(greet
)以某个单词"hello"开头,或者如果输入以h开头,我会使用if
语句打印某个输出.
我尝试过:
if greet == "hello":
print("wrong")
elif greet == "h_" #(but not hello)
print(" okay")
else:
print("good")
也可以使用.startswith()
:
if greet.startswith("hello"):
print("wrong")
elif greet.startswith("h"):
print("okay")
else:
print("good")
试试这个.它通过调用strip
忽略前导和尾随空格,它有一个条件,表示输入中没有放置任何内容,最后它不区分大小写,因为它将输入标准化为lower
:
greet = input().strip()
if len(greet) > 0:
firstWord = greet.split(" ")[0].lower()
if firstWord == 'hello':
print("wrong")
elif firstWord[0] == "h":
print("ok")
else:
print("good")
else:
print("You must enter something")
Nearly there but you need to do:
In particular
greet == "h_"
just checks to see if the user has entered literally"h_"
.