如果字符串只包含“或”

2024-03-28 13:20:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个小函数来检查输入的字符串是否是莫尔斯电码。 该函数应该执行以下操作: 如果“-”或“.”仅在输入的字符串中: 但我似乎找不到一种方法来做Python3上唯一的一点。 目前我实现这个的方法是非常凌乱而不是非常python

if "-" in message:
    # message might be morse code so check even more
        if "." in message:
            # Message IS morse code so return true
            return True
        else:
            # TODO you can use a REGEX for the below things
            if '--' in message:
                # if the messsage contains only hyphens, then check to see if
                # message contans hyphen only morse code by checking all hyphen
                # only morse code against message
                return True
            elif '-----' in message:
                # if message contains 0 in morse code, return True
                return True
    if "." in message:
        # message might contain morse code
        if "-" in message:
            # message IS morse code.
            return True
        else:
            # check to see if message is dots only morse code
            # TODO you can use a REGEX for the below things
            if ".." in message:
                # message IS Morse Code
                return True
            elif "..." in message:
                # message IS Morse Code
                return True
            elif "....":
            # message IS Morse Code
                return True
        # if dots or dash not in message, return none
        return("Message has no hyphens or full stops")

当我粘贴的时候,格式有点偏差,但这是基本要点。 当它检查信息是否是“---”或“.”等时,这是因为有些摩尔斯电码字母只是这些字符,但我相信有一个更简单的方法来绕过这个问题!在


Tags: the方法intruemessageonlymorsereturn
3条回答

您可以使用any()

def is_morse(message):
    return bool(message) and not any(ch not in '.- ' for ch in message)

bool(message)位也拒绝零长度的消息。在

def is_morse(message):
    allowed = {".", "-", " "}
    return allowed.issuperset(message)

但由于消息包含所有字符,并不意味着它是有效的。您需要检查每一个是否有效,您可以使用dict将字母映射到morse,您还需要一些明确的格式,即字母之间的空格和单词之间的2个或更多空格:

^{pr2}$

可以将它解析为一个得到所有变体的字符串,只需要做更多的工作。在

如果您想走另一条路,那么只需反转映射:

to_morse = {v: k for k, v in morse.items()}

def can_morse(msg):
    return all(ch in to_morse for ch in msg.upper())


msg = "Hello  World"
if can_morse(msg):
    print(" ".join([to_morse[ch] for ch in msg.upper()]))

我选择额外的空格来分隔单词,你可以选择任何你喜欢的,只要确保将字符添加到dict映射,然后添加到一个空格或任何你想用它来分隔单词的东西。在

检查message的每个元素是否在正确的字母表中:

if all(c in ['-', '.'] for c in message):

或将消息缩减为一组:

^{pr2}$

或者使用正则表达式:

if re.match('[-.]*$', message):

相关问题 更多 >