首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如果字符串只包含"-“或”。“

如果字符串只包含"-“或”。“
EN

Stack Overflow用户
提问于 2015-09-23 21:02:47
回答 6查看 797关注 0票数 0

我正在编写一个小函数,它检查输入的字符串是否为morse代码。该函数应该执行类似于"If "-“或”的操作,只在Inputted_string中执行:“但我似乎无法找到在Python3上执行唯一一步的方法。我目前的实现方式是非常混乱,而不是非常Pythonic

代码语言:javascript
运行
复制
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")

当我粘贴时,格式略有偏离,但这是一般的要点。当它检查消息是否为“--”或“.”时等等,这是因为一些摩尔斯电码字母只是那些牧师,但我相信有一个更容易的方法来解决这个问题!

EN

Stack Overflow用户

发布于 2015-09-23 21:07:10

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

代码语言:javascript
运行
复制
if all(c in ['-', '.'] for c in message):

或将消息还原为一组:

代码语言:javascript
运行
复制
if set(message) <= set(['.', '-'])

或者使用正则表达式:

代码语言:javascript
运行
复制
if re.match('[-.]*$', message):
票数 3
EN
查看全部 6 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32749428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档