(thanks to CoryKramer's code to the query on the post: morse code to english python3)
I am writing a morse code program. It works for string-to-morse. When making morse-to-string, it translates the morse properly but it ignores the whitespace, which I need for my output.
Here is my code:
def coder(text, to_morse=True):
morse_key = {'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': '--..',
'0': '-----', '1': '.----', '2': '..---',
'3': '...--', '4': '....-', '5': '.....',
'6': '-....', '7': '--...', '8': '---..',
'9': '----.', ' ': ' '
}
key_reversed = {value: key for key, value in morse_key.items()}
if to_morse:
return ' '.join(morse_key.get(i.upper()) for i in text)
else:
x = ''.join([key_reversed.get(i) for i in text.split() for i in (i, ' ')][:-1])
return str(x)
If for example, I do:
coder('-.. .- - .- ... -.-. .. . -. -.-. .', False)
it outputs:
'D A T A S C I E N C E'
However, the output that I want is:
'DATA SCIENCE'
How should I implement the split()
function whilst including whitespace?