python-3.x 忽略输入中除一个单词外的所有单词[已关闭]

thigvfpy  于 2023-02-01  发布在  Python
关注(0)|答案(3)|浏览(136)

昨天关门了。
这篇文章是昨天编辑并提交审查的。
Improve this question
如何忽略输入字符串中除第一个单词以外的所有单词?
例如,如果输入为"Hello",则程序应打印"input is Hello"。但是,如果输入为"Hello there",则还应打印"input is Hello"
我目前正在使用match-case语句,我已经尝试了几种方法,但我希望有更好的解决方案。
下面是我的代码:

match greeting:
    case "hello" + _:
        print("Greeting is Hello")
xcitsw88

xcitsw881#

您可能正在寻找类似这样的内容:

match greeting.split():
    case ['hello', *items]:
        print('greeting = hello')
        print('remaining: %s' % items)

它将匹配hello并收集剩余的项目。

niwlg2el

niwlg2el2#

有多种方法可以解决这个问题。第一种方法是拆分字符串并获取第一项,即hello

input_string = "Hello there"
words = input_string.split()
first_word = words[0]

Second approach use method stars with来自W3学校

input_string = "Hello there"
if input_string.startswith("Hello"):
    print("input = Hello")
nx7onnlm

nx7onnlm3#

entry = input().split()[0]
print("input =", entry)
  1. input()函数用于从用户处获取字符串,然后使用split()立即将该字符串拆分为单词列表。
    1.使用[0]提取列表中的第一个单词。

相关问题