- Translator
- Python
Morse code in Python
In Python, keep the codes in a dictionary: look each letter up to encode, reverse the dictionary to decode, and multiply the dot length by 1, 3 or 7 for timing. This guide has a short program using only the standard library, with the output of a real run.
In short: store the codes in a dictionary, look each letter up to encode, flip the dictionary around to decode, and turn dots and dashes into milliseconds to play them. The standard library is enough: no installs.
A Morse dictionary in Python
A Python dictionary stores pairs of a key and a value, and a lookup by key returns the value (Python Tutorial). That is all a translator needs: the letter is the key and its code is the value. The table below holds the 26 letters and 10 digits of the international code (ITU-R M.1677-1). Punctuation has codes too; the Morse code alphabet and Morse code punctuation list them. The dictionary text was generated from this site's own table, not typed by hand.
Save this as morse.py:
MORSE = {
"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": "----.",
}
REVERSE = {code: char for char, code in MORSE.items()}
def encode(text):
words = text.upper().split()
return " / ".join(" ".join(MORSE[char] for char in word) for word in words)
def decode(morse):
words = morse.split(" / ")
return " ".join("".join(REVERSE.get(code, "?") for code in word.split()) for word in words)
def timing(morse, wpm=12):
if wpm <= 0:
raise ValueError("wpm must be positive")
unit = 1200 / wpm # one unit in milliseconds
steps = [] # (is_on, milliseconds)
for word_index, word in enumerate(morse.split(" / ")):
if word_index:
steps.append((False, 7 * unit))
for letter_index, letter in enumerate(word.split()):
if letter_index:
steps.append((False, 3 * unit))
for sign_index, sign in enumerate(letter):
if sign_index:
steps.append((False, unit))
steps.append((True, (3 if sign == "-" else 1) * unit))
return steps
if __name__ == "__main__":
morse = encode("Hello world")
print(morse)
print(decode(morse))
steps = timing(encode("SOS"))
print(sum(1 for on, _ in steps if on), "signals,", round(sum(ms for _, ms in steps)), "ms")
Three functions sit on top of the dictionary. encode makes the text uppercase, splits it into words and joins the codes with a space between letters and a slash between words. decode reverses that, using a second dictionary built with a dict comprehension, which creates a dictionary from key and value expressions (Python Tutorial). timing comes in a moment.
Run python3 morse.py and you get this, from a real run:
.... . .-.. .-.. --- / .-- --- .-. .-.. -..
HELLO WORLD
9 signals, 2700 ms
Encode and decode: what can go wrong
Looking up a key that is not in the dictionary raises a KeyError, and get() returns a default instead (Python Tutorial). The sample uses both on purpose. encode lets the error through, so a character without a code stops the script instead of silently vanishing from your message. A comma, an apostrophe, an accented letter such as é, or an emoji raises KeyError, because the dictionary holds only A to Z and 0 to 9. decode uses get and prints a question mark for a code it does not know, which suits noisy input such as a key you tap by hand. Format matters too: decoding accepts whitespace between letters and expects a space, slash, space between words. A slash without those surrounding spaces is treated as an unknown letter. Some characters change when uppercased: ß, for example, becomes SS before lookup. To check results by eye, open the same text in the translator.
Timing: from dots and dashes to milliseconds
The international standard fixes the proportions: a dash lasts three times a dot, the gap inside a letter is one dot, between letters three and between words seven (ITU-R M.1677-1). A speed in words per minute then sets one unit, the length of a dot: 1200 divided by the speed gives milliseconds (ARRL, QEX, April 1990). The timing function returns a list of steps, each a pair: whether the signal is on, and for how many milliseconds. SOS at 12 WPM comes out as 9 signals and 2,700 ms, which is the last line of the output above. Here SOS is encoded as three ordinary letters, with the letter gaps defined above. Other speeds scale the same list:
| Speed | One unit | A dash | SOS |
|---|---|---|---|
| 5 WPM | 240 ms | 720 ms | 6,480 ms |
| 12 WPM | 100 ms | 300 ms | 2,700 ms |
| 20 WPM | 60 ms | 180 ms | 1,620 ms |
The list is plain data, so you can send it anywhere: flash an LED, drive a buzzer or write sound. Morse code timing explains the rules behind the numbers.
Write the sound to a WAV file
Python's wave module reads and writes WAV files. For a file you set the number of channels, the sample width in bytes and the frame rate, then write the frames (Python documentation, wave). The script below turns the timing list into a 8,000 Hz mono file: a 600 Hz sine wave while the signal is on, silence while it is off. Save it next to morse.py as sound.py:
import math
import struct
import wave
from morse import encode, timing
RATE = 8000 # samples per second
PITCH = 600 # hertz
VOLUME = 12000 # a 16-bit sample goes up to 32767
samples = []
for is_on, ms in timing(encode("SOS")):
for n in range(round(RATE * ms / 1000)):
samples.append(round(VOLUME * math.sin(2 * math.pi * PITCH * n / RATE)) if is_on else 0)
with wave.open("sos.wav", "wb") as out:
out.setnchannels(1) # mono
out.setsampwidth(2) # 16-bit samples
out.setframerate(RATE)
out.writeframes(struct.pack(f"<{len(samples)}h", *samples))
print(len(samples), "samples =", len(samples) / RATE, "seconds")
The real output is:
21600 samples = 2.7 seconds
Open sos.wav in any audio player. The length matches the timing list exactly: 2,700 ms at 8,000 samples per second is 21,600 samples. At other speeds or pitches, a tone can start or stop mid-wave and click slightly; a short fade at each edge avoids that.
Where to go from here
The same timing list drives hardware. Morse code with Arduino blinks an LED and sounds a buzzer from a microcontroller sketch, and Morse code with Raspberry Pi sends the list to an LED on a Raspberry Pi and reads a key button. If you only want to hear what your code makes, the translator plays any text, and learning Morse by ear shows how the real thing sounds.
Sources
- Recommendation ITU-R M.1677-1, International Morse code. ITU Radiocommunication Sector, October 2009.
- A Standard for Morse Timing Using the Farnsworth Technique, Jon Bloom, KE3Z. ARRL, QEX, April 1990.
- The Python Tutorial, 5.5. Dictionaries. Python Software Foundation, docs.python.org, checked 7 November 2026.
- wave: Read and write WAV files, The Python Standard Library. Python Software Foundation, docs.python.org, checked 7 November 2026.