C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The letters A, B and C have sequential numbers. This is how they are stored in ASCII.
Note 2: The number strings 1, 2 and 3 are made of characters that are represented in ASCII by 49, 50 and 51.
Python program that uses ord built-in
letters = "ABCabc123"
for letter in letters:
# Get number that represents letter in ASCII.
number = ord(letter)
print(letter, "=", number)
Output
A = 65
B = 66
C = 67
a = 97
b = 98
c = 99
1 = 49
2 = 50
3 = 51
Here: We convert 97 back into the lowercase "a." This code could be used to round-trip letters and digits.
Python program that uses chr
numbers = [97, 98, 99]
for number in numbers:
# Convert ASCII-based number to character.
letter = chr(number)
print(number, "=", letter)
Output
97 = a
98 = b
99 = c
So: We generate translation keys and values with an algorithm, and then apply the generated table to translate strings.
Python program that uses chr, maketrans, translate
# Generate string for translation.
initial = ""
for i in range(97, 97 + 26):
initial += chr(i)
# Generate mapped chars for string.
translated = ""
for i in range(97, 97 + 26):
translated += chr(i - 10)
print("INITIAL ", initial)
print("TRANSLATED", translated)
# Create a lookup table.
table = str.maketrans(initial, translated)
# Translate this string.
value = "thank you for visiting"
result = value.translate(table)
print("BEFORE", value)
print("AFTER ", result)
Output
INITIAL abcdefghijklmnopqrstuvwxyz
TRANSLATED WXYZ[\]^_`abcdefghijklmnop
BEFORE thank you for visiting
AFTER j^Wda oek \eh l_i_j_d]
Also: Ord and chr built-ins help transform characters and strings. But they are not ideal for all translations.
ROT13Translate: With maketrans and translate() we can translate strings. We can use chr and ord to build translation strings for these methods.
Translate