I currently have a dictionary of morse code letters, and i want to be able to change a user input string into corresponding morse code characters. Is there any easy way to accomplish this in python?
4 Answers
morse = {"A": ".-", "B": "-...", "C": "-.-."} #etc.
text = "ABC"
output = " ".join(morse[letter] for letter in text)
You might want to use letter.upper() if input can also be lowercased. And if you don't have all morse characters in your table, you might want to compensate for that, too (credits go to ThiefMaster for this!), so the end result could be
output = " ".join(morse[letter] for letter in text.upper() if letter in morse)
1 Comment
Duncan
Your test also needs to be
if letter.upper() in morse otherwise lowercase won't be translated.It's easy:
input = 'a string'
morse_code = { ... }
print ' '.join( [morse_code[i] for i in input] )
2 Comments
Simone
@eumiro I didn't get your comment.
eumiro
run your code (with two or three letters in the
morse_code dictionary) and you will see. ''.join(...) joins the elements without space between them. The spaces between letters in the Morse code are important. Replace ''.join with ' '.join