2

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

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

2 回答 2

3

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

match user.split():
    case ["cesar", *mot]:
        cesar(mot)
    case _:
        print("your answer is incorrect")
于 2021-10-29T19:58:04.903 回答
1

对于“一个变量中的所有文本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'
于 2021-10-30T06:38:54.960 回答