【问题标题】:How to take string with space in match case in Python 3.10如何在 Python 3.10 中的匹配情况下获取带空格的字符串
【发布时间】:2021-12-14 20:07:36
【问题描述】:

我在 python 3.10 中有一个带有匹配案例结构的代码。这是一个终端的应用程序,带有命令。如何在一个变量中获取“cesar”之后的所有文本?因为空格会破坏命令。

user= input("->")
match user.split():
    case["cesar" ,mot]:
        cesar(mot)
    case _:
        print("your answer is incorrect")

【问题讨论】:

  • 离题,但如果您不想重新发明轮子,可以使用cmd library

标签: python match python-3.10


【解决方案1】:

使用* 匹配子列表,就像在函数参数列表中获取所有剩余参数一样。

match user.split():
    case ["cesar", *mot]:
        cesar(mot)
    case _:
        print("your answer is incorrect")

【讨论】:

    【解决方案2】:

    对于“一个变量中cesar之后的所有文本”,如果您的意思是一个str变量,请使用maxsplit=1;否则,Barmar 的答案可能就是您想要的:

    def cesar(mot):
        print(f'{mot=}')
    
    user= input("->")
    match user.split(maxsplit=1):
        case["cesar" ,mot]:
            cesar(mot)
        case _:
            print("your answer is incorrect")
    

    输出:

    ->cesar one two three
    mot='one two three'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2022-12-29
      • 1970-01-01
      • 2019-06-11
      相关资源
      最近更新 更多