搜索字符串并将其转换为另一个字符串python

时间:2016-02-05 12:39:30

标签: python-3.x

def parse_shot_success(string):
    """
    Determine if the shot was successful.
    Input:
        string: a string to be analyzed
    Returns:
        "scores" or "misses" or "not a shot" based on
        the shot success.
    """
    pp = re.compile("(scores|misses|blocks)")
    match = pp.search(string)
    if match.group(1) == "scores":
        return "scores"
    elif match.group(1) == ("blocks|misses"):
        return "misses"
    else:
        return "not a shot"

嗨,我想回复"未命中"或"得分"基于玩家是否在字符串中得分或错过,以便parse_shot_success("Johnson blocks Lebron's shot")将返回未命中。我想我必须使用for loop,但我不确定如何将其合并到我的代码中。你能帮我谢谢。

1 个答案:

答案 0 :(得分:1)

如果你真的想要使用正则表达式:

def parse_shot_success(string):
    pp = re.compile("(scores|misses|blocks)")
    match = pp.search(string)

    if not match:
        # https://docs.python.org/dev/library/re.html#re.search
        # "Return None if no position in the string matches the pattern"
        return "not a shot"
    elif match.group(1) == "scores":
        return "scores"
    elif match.group(1) in ("blocks", "misses"):
        return "misses"
    else:
        raise AssertionError

但是这个问题可以通过其他方式轻松解决:

def parse_shot_success(string):
    if 'scores' in string:
        return 'scores'
    elif 'blocks' in string or 'misses' in string:
        return 'misses'
    else:
        return 'not a shot'

或者:

def parse_shot_success(string):
    words = [
        # (word, return value)
        ('scores', 'scores'),
        ('blocks', 'misses'),
        ('misses', 'misses'),
    ]

    for word, result in words:
        if word in string:
            return result

    return 'not a shot'

您有一些未考虑的问题:

  • 如果我给你字符串"SCORE"(大写)?
  • 怎么办?
  • 如果有名字为" blocksmith"的玩家怎么办? (包含单词" blocks")?这种情况下使用正则表达式可能是最简单的方法。