【问题标题】:How to find letters in order from a string in Python 2.7如何从 Python 2.7 中的字符串中按顺序查找字母
【发布时间】:2017-10-04 22:42:14
【问题描述】:

对于我在 Python 2.7 中制作的项目,我必须编写一些东西来判断字母“i”和“a”是否出现在用户输入的字符串中。字母必须按该顺序排列,但它们不必是连续的(中间可以有其他字母)。我将如何对其进行编码,以便它可以检测字符串中的那组条件?

到目前为止,我所拥有的是这个......

name = easygui.enterbox("string being searched");
term1 = "i";
number = name.find(term1)
term2 = "a";
number = name.find(term2)
if(number > 1):
    easygui.msgbox("message")
    bonus = True
else:
    bonus = False

...但它没有考虑字母的顺序。我已经解决了许多类似类型的问题,但都没有奏效。

【问题讨论】:

  • 字符串中可以有多个“i”或“a”吗?这些案例的预期结果是什么?

标签: python string python-2.7


【解决方案1】:

您会找出第一个字母第一次出现的位置(以及是否),然后从该位置搜索第二个字母。

str.find 有一个可选的起始参数,您可以使用它来指定搜索第二个字母的起始位置。

【讨论】:

    【解决方案2】:

    find 字符串方法为您提供子字符串第一次出现的索引。如果找不到,则返回-1。

    name = easygui.enterbox("string being searched")
    term1 = 'i'
    term2 = 'a'
    position1 = name.find(term1)
    position2 = name.find(term2)
    if(position1 != -1 and position2 != -1 and position1 < position2):
        easygui.msgbox("message")
        bonus = True
    else:
        bonus = False
    

    【讨论】:

    • 谢谢!效果很好,感谢您的帮助。
    • 很高兴能帮上忙!如果您满意,请接受正确的答案。
    【解决方案3】:

    如前所述,find 方法返回索引。不过,这可能很有用。不要使用在原始代码中被覆盖的 number 值,只需检查成员资格。我们可以在 if 语句中使用 in 来做到这一点。

    # set the value as a string just for easy use
    name = 'i am super'
    
    # check for membership of both "i" and "s"
    if 'i' in name and 's' in name:
    
        # Now use the .find method to check the indexes and make sure they are in the order you want (i before a or in this case s).
        if name.find('i') < name.find('s'):
    
            # print the indexes just to 2x check
            print(name.find('i'))
            print(name.find('s'))
    
            # if both conditions are valid, print True, here's where you'd assign bonus to True
            print('True')
        else:
            # print or assign bonus to false.
            print('False')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 2014-11-26
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多