how to separate characters only if they have spaces between them?

Question:

I’m making a morse code translator in python, and I successfully created a program that translates words into morse code, but now I want to make an option to translate morse code into words. while I was doing so, I realized that if I wanted to translate a letter that uses more than 2 characters, it printed out the letters e and t. I deducted that this was caused by adding every character into a list and translating those separately. Is there a way i can check if there is a space between characters and separating them only if there is?

Here is my code so far:

codes = { ' ':'  ', 'A':'.-', 'B':'-...',
                'C':'-.-.', 'D':'-..', 'E':'.',
                'F':'..-.', 'G':'--.', 'H':'....',
                'I':'..', 'J':'.---', 'K':'-.-',
                'L':'.-..', 'M':'--', 'N':'-.',
                'O':'---', 'P':'.--.', 'Q':'--.-',
                'R':'.-.', 'S':'...', 'T':'-',
                'U':'..-', 'V':'...-', 'W':'.--',
                'X':'-..-', 'Y':'-.--', 'Z':'--..',
                '1':'.----', '2':'..---', '3':'...--',
                '4':'....-', '5':'.....', '6':'-....',
                '7':'--...', '8':'---..', '9':'----.',
                '0':'-----', ', ':'--..--', '.':'.-.-.-',
                '?':'..--..', '/':'-..-.', '-':'-....-',
                '(':'-.--.', ')':'-.--.-'}
ask = input("A: translate english to code nB: translate code to english").upper()
if ask == "A":
    i = input("")
    mylist = list(i)
    for i in mylist:
        if i == " ":
            print(codes[i], end="", flush=True)
        else:
            print(codes[i.upper()] + " ", end="", flush=True)
elif ask == "B":
    print("Make sure to add 1 space between letters and 2 spaces between words!")
    i = input("")
    mylist = list(i)
    key_list = list(codes.keys())
    val_list = list(codes.values())
    for i in mylist:
        position = val_list.index(i)
        print(key_list[position], end="", flush=True)



        
Asked By: Synt4xErr0r 7

||

Answers:

The str.split() method without an argument splits on whitespace

Answered By: Gabriel

Here’s a simplification of your code.

# Modified to make ' ' entry be just single space 
# This allows us to add a space after every character rather than treating space as special when generating Morse code
codes = { ' ':' ', 'A':'.-', 'B':'-...',
                'C':'-.-.', 'D':'-..', 'E':'.',
                'F':'..-.', 'G':'--.', 'H':'....',
                'I':'..', 'J':'.---', 'K':'-.-',
                'L':'.-..', 'M':'--', 'N':'-.',
                'O':'---', 'P':'.--.', 'Q':'--.-',
                'R':'.-.', 'S':'...', 'T':'-',
                'U':'..-', 'V':'...-', 'W':'.--',
                'X':'-..-', 'Y':'-.--', 'Z':'--..',
                '1':'.----', '2':'..---', '3':'...--',
                '4':'....-', '5':'.....', '6':'-....',
                '7':'--...', '8':'---..', '9':'----.',
                '0':'-----', ', ':'--..--', '.':'.-.-.-',
                '?':'..--..', '/':'-..-.', '-':'-....-',
                '(':'-.--.', ')':'-.--.-'}

# Generate reverse code table (i.e. to go from Morse code to english)
codes_rev = {v:k for k, v in codes.items()}

ask = input("A: translate english to code nB: translate code to english").upper()
if ask == "A":
    for letter in input("enter text: ").upper():        # can apply upper to all letters (leaves space unchanged)
        # We space a space against all letters
        print(codes[letter] + ' ', end="")    # all letters are followed by a space
                                              # this cause a space to be two spaces
       
elif ask == "B":
    print("Make sure to add 1 space between letters and 2 spaces between words!")

    for word in input("enter morse code: ").split('  '):   # Words are separated by double spaces
        for letter in word.split(' '):                     # letters are separated by single spaces    
            if letter:                                     # handles case of empty string on split at end of line
                print(codes_rev[letter], end="")
            
        print(' ', end = "")    # space between words
else:
    print('A or B should le entered')

Usage

Encoding

A: translate english to code 
B: translate code to englisha
enter text: A journey of a thousand miles begins with a single step.
.-   .--- --- ..- .-. -. . -.--   --- ..-.   .-   - .... --- ..- ... .- -. -..   -- .. .-.. . ...   -... . --. .. -. ...   .-- .. - ....   .-   ... .. -. --. .-.. .   ... - . .--. .-.-.- 

Decoding

A: translate english to code 
B: translate code to englishb
Make sure to add 1 space between letters and 2 spaces between words!
enter morse code: .-   .--- --- ..- .-. -. . -.--   --- ..-.   .-   - .... --- ..- ... .- -. -..   -- .. .-.. . ...   -... . --. .. -. ...   .-- .. - ....   .-   ... .. -. --. .-.. .   ... - . .--. 
A JOURNEY OF A THOUSAND MILES BEGINS WITH A SINGLE STEP 
Answered By: DarrylG
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.