将一个字符串与另一个字符串的多个子字符串进行比较

30

是否有另一种更简单的编码方式,可以基本检查字符串'abcde'的每个字符?

if input == 'a' or input == 'ab' or input == 'abc' or input == 'abcd' or input == 'abcde':
    return True

它们可以是“abcde”的多个组合吗?比如 input=='de'? - McLovin
2
请不要将 input 作为您的变量名称。 - Diptangsu Goswami
5个回答

37

这应该做与您输入的相同的事情。

return 'abcde'.startswith(input)

1
从描述中,不清楚空字符串的结果应该是什么,"abcde".startswith("") == True,这与示例代码不太匹配。 - Joe
2
如果你不想包含空字符串,我认为最好的方法是添加一个 and input - duckboycool

12

不要将变量命名为input,因为它会遮盖内置函数input()。这被认为是一种不好的做法,而且很容易选择另一个变量名。

您可以使用集合来检查输入是否与任何子字符串匹配:

lookups = {'a', 'ab', 'abc', 'abcd', 'abcde'}

my_input = input()

if my_input in lookups:
    return True
我们也可以使用集合推导式生成该集合:
characters = 'abcde'

lookups = {characters[:i] for i in range(1, len(characters) + 1)}

my_input = input()

if my_input in lookups:
    return True

使用集合而不是列表,对于包含大量组合的情况,好处在于你可以获得常数时间 O(1) 的查找速度。这比使用列表要好得多,因为列表会给出线性 O(N) 的查找速度。


6

有多种可爱的方法可以实现。 startwith 可能是最有效的方法,但这些方法也可以工作:

使用 lstrip:

return 'abcde'.lstrip(input)!='abcde'

使用列表推导(list comprehension):
return any(['abcde'[:i+1] == input for i in range(len('abcde'))])

使用正则表达式:

   pattern = re.compile('^'+input)
   return bool(pattern.match('abcde'))

或者只是:

  return 'abcde'[:len(input)]==input

“not not pattern.match(...)”是什么意思?如果您只是想将match转换为bool类型,您可以直接使用“bool”:bool(pattern.match(...)) - Asocia

5

您可以尝试类似于以下方式:

def your_function():
    # Add as much chars that you want here
    chars = "abcde"

    # Assuming you are taking the user input from terminal
    user_input = input()

    # Loop over every substring from chars
    for i in range(len(chars) + 1):
        if chars[:i] == user_input:
            return True

    return False

如果这有帮到你,请让我知道!


0
你可以尝试这个:
If input in ['a', 'ab', 'abc', 'abcd', 'abcde']:
    return True
else:
   return False

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接