Last week a friend restoring a 1970s boat radio handed me a photocopy from the service manual: three lines of dots and dashes, no letters, and a pencil note that just said “test message”. He wanted to know what it said before he trusted the receiver. I could have decoded forty characters by eye, but I type faster than I read Morse, so I wrote a script instead.
That turned into a more interesting afternoon than I expected. Morse looks trivial from the outside — two symbols and a few spaces. The encoding rules have more corners than that, and I ran into three of them within an hour. Here is what worked, what failed, and the shortcut I use now when I don’t want to open an editor at all.
The whole encoder is a lookup table. This is the version that lives in my ~/bin on Ubuntu 22.04, Python 3.11.1:
# morse.py — Python 3.11.1
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 = {v: k for k, v in MORSE.items()}
def encode(text: str) -> str:
words = []
for word in text.upper().split(" "):
letters = [MORSE[ch] for ch in word if ch in MORSE]
if letters:
words.append(" ".join(letters))
return " / ".join(words)
def decode(morse: str) -> str:
out = []
for word in morse.strip().split(" / "):
out.append("".join(REVERSE.get(tok, "?") for tok in word.split()))
return " ".join(out)
if __name__ == "__main__":
msg = "SOS WE ARE SINKING"
print(encode(msg))
print(decode(encode(msg)))
Running it:
$ python3 morse.py
... --- ... / .-- . / .- .-. . / ... .. -. -.- .. -. --.
SOS WE ARE SINKING
The round trip is the first thing I check in any encoder. If encode → decode does not reproduce the input, nothing else in the file matters. The ? fallback makes table typos show up immediately instead of silently producing garbage.
For the letter table I copied the ITU-R M.1677 recommendation, the international standard. Keep it open in a tab: several “cheat sheet” pages on the web quietly disagree with it on punctuation, and you only find out when a decode comes back wrong.
For a small web project I ported it to JavaScript, as an ES module (Node v22.13.0):
// morse.mjs — Node v22.13.1
const MORSE = new Map([
["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", "----."],
]);
const REVERSE = new Map([...MORSE].map(([k, v]) => [v, k]));
export const encode = (t) =>
t.toUpperCase().split(" ")
.map((w) => [...w].filter((c) => MORSE.has(c)).map((c) => MORSE.get(c)).join(" "))
.filter(Boolean).join(" / ");
export const decode = (m) =>
m.trim().split(" / ")
.map((w) => w.split(" ").map((tok) => REVERSE.get(tok) ?? "?").join(""))
.join(" ");
console.log(encode("CQ CQ DE M0XYZ K"));
console.log(decode("-.-. --.-"));
Output on my box:
$ node morse.mjs
-.-. --.- / -.-. --.- / -.. . / -- ----- -..- -.-- --.. / -.-
CQ
M0XYZ is a legal amateur callsign shape, and the digit 0 encodes as -----, so mixed letter-digit words work without special cases.
For my friend’s radio manual I did not keep a Python session open. Three lines, once — booting an editor felt like overhead. I pasted the sequence into a free online morse code translator, set the letter and word gap conventions the manual used, and had the answer in seconds: “TEST 7413”, which matched the numbers stamped inside the radio’s case. Case closed in under a minute.
I still reach for this browser-based translator whenever the input came from a human rather than a file. Real-world Morse is messy: people separate words with /, with three spaces, or with nothing at all, and I would rather toggle conventions in a UI than re-edit my split() calls for the fifth time. It runs entirely client-side, so the text never leaves the page — irrelevant for a dead radio manual, but the habit matters when the message is not mine to upload anywhere.
1. str.translate() cannot hold this table. My first Python attempt used a translation table so I could call text.translate(TABLE) in one shot. Python rejected it at import time:
ValueError: string keys in translate table must be of length 1
That is by design. translate maps one Unicode code point to another, and ".-" is two characters. A plain dict with an explicit loop is the honest tool here; the one-liner is not worth fighting the type system for.
2. Spacing is data, not decoration. Letter gaps and word gaps carry meaning, and losing one changes the message. Decode ... --- ... with my script and you get SOS. Merge the gaps into one token, ...---..., and the same dots and dashes produce:
?
No single token matches the merged string, so the fallback fires. If a sender compresses spacing, you do not get a wrong answer — you get nothing, which is quieter and more dangerous. Always find out which convention your source uses before trusting a decode.
3. Accented characters crash or vanish. The ITU table covers A–Z, 0–9 and a handful of punctuation marks. My first encode version had no character filter, and one input containing “CAFÉ” produced:
Traceback (most recent call last):
File "morse.py", line 33, in encode
letters = [MORSE[ch] for ch in word]
KeyError: 'É'
Two options: strip accents first with unicodedata.normalize("NFKD", text).encode("ascii", "ignore"), or keep the if ch in MORSE filter and log what you dropped. Extended Morse tables do define é (..-..), but if your receiving side does not know them, transmitting it just moves the failure downstream. Decide once, at the boundary, and be explicit about it.
| Approach | Best for | What I ran |
|---|---|---|
| Python dict script | batch files, repeat jobs | Python 3.11.1, Ubuntu 22.04 |
| Node ES module | embedding in a web app | Node v22.13.0 |
| Browser tool | one-off decode, messy human input | Chromium, nothing to install |
The boat radio message turned out to be a factory test string from 1974. My friend was mildly disappointed it was not a distress call. I was just glad the round trip matched.
More free browser-based utilities at utilvy.com.