【问题标题】:How to check a part of an input | Python [duplicate]如何检查输入的一部分 | Python [重复]
【发布时间】:2021-06-15 17:37:22
【问题描述】:

我想检查输入的特定部分,但我不知道它在“哪里”

我试过这个: a = input('输入命令')

if a[0:5] == '(Command name)':

    if a[7:?] == '(Subject)':

        if a[?:len(a)] == '(Choice)':

            To be continued

所以,输入分为三部分;命令、主题以及它将运行的命令类型。 但是应该使用哪个索引?是?我不知道这个词的长度。不可能吗?

不,我知道我能做到,只是不知道怎么做。

【问题讨论】:

标签: python list input indexing


【解决方案1】:

我想你的输入应该是这样的:

command subject choice

所以基本上有三个部分(可能更多)。我建议您将列表中的输入分解为:

a = [str(x) for x in input().split()]

获取每个实体的长度:

len(entity)

对于索引,您可以使用 index():

list.index(entity)

【讨论】:

    【解决方案2】:

    如果它们总是一个词,也许这样的事情会起作用:

    terms = a.strip().split(" ")
    command_name = terms[0]
    subject = terms[1]
    choice = terms[2]
    

    如果有双空格的可能,那就需要更巧妙了


    以上同

    command_name, subject, choice = a.strip().split(" ")
    

    【讨论】:

    • 哇,你的答案真的很快。谢谢
    • 顺便说一句,你的意思是command_name = terms[0]?
    • 哦是的 - 现已修复
    猜你喜欢
    • 2014-11-05
    • 2017-01-31
    • 1970-01-01
    • 2020-08-04
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    相关资源
    最近更新 更多