Quick Overview
`str.translate()` walks the string once against a lookup table, where chained `.replace()` calls walk it once each. The table also cannot re-replace a character an earlier pass produced.
Create a function hacker_speak(txt) that takes a string as an argument and returns a coded (h4ck3r sp34k) version:
"a" becomes "4""e" becomes "3""i" becomes "1""o" becomes "0""s" becomes "5"Replacing specific character mappings is used in text sanitization, password strength generators, and template rendering.
Use a dictionary mapping paired with str.maketrans() and str.translate():
def hacker_speak(txt):
mapping = str.maketrans({"a": "4", "e": "3", "i": "1", "o": "0", "s": "5"})
return txt.translate(mapping)
# Testing our function
print(hacker_speak("javascript is cool")) # Output: "j4v45cr1pt 15 c00l"
print(hacker_speak("programming is fun")) # Output: "pr0gr4mm1ng 15 fun"
print(hacker_speak("become a coder")) # Output: "b3c0m3 4 c0d3r"
str.translate() runs in fast C-level speed, replacing all matched characters in a single pass across the string!
txt.replace("a", "4").replace("e", "3")... works for small strings, but creates multiple intermediate string allocations in memory. Use str.translate() for bulk character replacements.Use str.translate() for bulk replacements. Next, let's count character occurrences in a string!
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.