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

问题描述 投票:5回答:5

有没有其他更简单的方法来编写基本上检查字符串的每一个字符的代码?'abcde'

if input == 'a' or input == 'ab' or input == 'abc' or input == 'abcd' or input == 'abcde':
    return True
python string string-comparison
5个回答
37
投票

这应该和你放的东西一样。

return 'abcde'.startswith(input)

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'))])

使用 regex:

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

或只是。

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

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
© www.soinside.com 2019 - 2024. All rights reserved.