Master character mapping and string replacement in Python using str.translate() or dictionary mappings.
Learn how to convert minutes into seconds in Python using arithmetic multiplication and basic unit conversions.
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!