当前位置:优学网  >  在线题库

如何使用if语句输入以某个字母开头的内容

发表时间:2022-07-28 00:59:11 阅读:253

如果用户输入(greet)以某个单词"hello"开头,或者如果输入以h开头,我会使用if语句打印某个输出.

我尝试过:


if greet == "hello":
    print("wrong") 
elif greet == "h_" #(but not hello)
    print(" okay")
else: 
    print("good")
🎖️ 优质答案
  • Nearly there but you need to do:

    if greet == "hello":
        print("wrong")
    elif greet[0] == "h":
        print("okay")
    else:
        print("good")

    In particular greet == "h_" just checks to see if the user has entered literally "h_".

  • 也可以使用.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")
    
  • 相关问题