string_translate_01.py

#! /usr/bin/python3
# ===================================================================
# python string translate and maketrans
#
# Note: unicode characters 0 to 127 are the same as ASCII 0 to 127
#
# Code example from: www.youtube.com/watch?v=ZCoHZNg3RPk
# ===================================================================

string = 'hello guys and welcome'

# -------------------------------------------------------------------
# ----create translation table
# -------------------------------------------------------------------

# ---- table key are unicode characters, values are unicode characters
dict1 = { 'a':'1', 'b':'2', 'c':'3', 'd':'4' }
# ---- table key are uniccode ordinals, values are unicode characters
dict2 = { 97:'1', 98:'2', 99:'3', 100:'4' }
# ---- table key are unicode characters, values are unicode ordinals
dict3 = { 'a':87, 'b':88, 'c':89, 'd':90 }

table1 = string.maketrans(dict1)
table2 = string.maketrans(dict2)
table3 = string.maketrans(dict3)

print()
print(f'table1   = {table1}')
print(f'table2   = {table2}')
print(f'table3   = {table3}')
print(f'chr(90)  = {chr(90)}')
print(f'chr(100) = {chr(100)}')

# -------------------------------------------------------------------
# ---- translate the string
# -------------------------------------------------------------------

s1 = string.translate(table1)
s2 = string.translate(table2)
s3 = string.translate(table3)

print()
print(f's1 = {s1}')
print(f's2 = {s2}')
print(f's3 = {s3}')
print()