类型:列表元组

描述

摩尔斯电码(又译为摩斯密码,Morse code)是一种时通时断的信号代码,通过不同的排列顺序来表达不同的英文字母、数字和标点符号。

编写程序,把输入的英文句子转换成摩尔斯电码并输出电码字符串。

本题只需要对英文字母(不区分大小写)进行编码转换,其他字符原样输出。

下面列表中为26个英文字母对应的摩尔斯电码。

[".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.",
"---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]

示例 1

输入:

How are you?

输出:   

....---.-- .-.-.. -.-----..-?

参考答案

# def ciphertext(plaintext):
#     ls=[".-","-...","-.-.","-..",".","..-.","--.","....",
#         "..",".---","-.-",".-..","--","-.","---",".--.",
#         "--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
#     plaintext = plaintext.lower()
#     letter = 'abcdefghijklmnopqrstuvwxyz'
#     for c in plaintext:
#              if c in letter:
#                        plaintext = plaintext.replace(c,ls[letter.find(c)])
#     return plaintext


# if __name__ == '__main__':
#     plaintext = input()
#     print(ciphertext(plaintext))



def ciphertext(plaintext):
    ls=[".-","-...","-.-.","-..",".","..-.","--.","....",
        "..",".---","-.-",".-..","--","-.","---",".--.",
        "--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
    plaintext = plaintext.lower()                 # 字符串中所有字母转小写
    message = ''
    for c in plaintext:
        if 'a' <= c <= 'z':                       # 判定 c 是不是小写字母
            message =  message + ls[ord(c)-97]    # ord(c) 返回代表它 Unicode 码的整数,减97后落入0-25的区间
        else:
            message =  message + c                # 非小写字母时不做变换,直接拼接原字符
    return message


if __name__ == '__main__':
    plaintext = input()                          # 输入一个字符串
    print(ciphertext(plaintext))                 # 调用函数,并输出返回值
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐