1

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?

1
  • 5
    What do you have so far, and how doesn't it work? Commented Feb 8, 2011 at 10:33

4 Answers 4

6
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)
Sign up to request clarification or add additional context in comments.

1 Comment

Your test also needs to be if letter.upper() in morse otherwise lowercase won't be translated.
2
newStr = ' '.join(morseDict[c] for c in oldStr if c in morseDict)

This will silently delete all chars which are not keys in morseDict

Edit: now adding whitespace between the "letters". You'll want to map ' ' to e.g. a tab or multiple spaces to have a word separator.

Comments

0
morse = {
"a": ".-",
"b": "-...",
"c": "-.-.",
...
...
}

str = "Hello"

for ch in str:
    print morse[ch.lower()],

Comments

0

It's easy:

input = 'a string'
morse_code = { ... }

print ' '.join( [morse_code[i] for i in input] )

2 Comments

@eumiro I didn't get your comment.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.