2022-10-13_python-string-translate.html


001| #:name::Python String Translate
002| #:link::https://thehardcorecoder.com/2022/10/13/python-string-translate/
003| #:date::2022-10-13
004| #:code::
005| def translate_string (s_orig, t_map=[]):
006|     '''Simulation of str.translate() method.'''
007|     buf = []
008|     for char in str(s_orig):
009|         cnum = ord(char)
010|         try:
011|             cout = t_map[cnum]
012|             if cout is None:
013|                 continue
014|         except:
015|             cout = cnum
016|         sout = cout if isinstance(cout,str) else chr(cout)
017|         buf.append(sout)
018|     return ''.join(buf)
019| 
020| #:code::
021| s = '''Samantha Ann Bear
021| 13924 Schulte Way
021| Apt. 2402
021| Forest City, CA 92508
021| [code:QRTD8945-2740-21]'''

022| 
023| ts = [
024|     s.translate({}),
025|     s.translate({32:32}),
026|     s.translate({32:'_'}),
027|     s.translate({32:None}),
028| 
029|     s.translate(''),
030|     s.translate('aeiou'),
031| 
032|     s.translate([]),
033|     s.translate([0,1,2,3,4,5,6,7,8,9]),
034| 
035|     s.translate(()),
036|     s.translate(('','a','b','c','d')),
037| ]
038| 
039| for t in ts:
040|     print(t)
041|     print()
042| 
043| print()
044| 
045| #:code::
046| s='<p>"<strong>Hello</strong>, <em>World</em>!" (&U2!)</p>'
047| 
048| html_string_map = {
049|     ord('&'): '&amp;',
050|     ord('<'): '&lt;',
051|     ord('>'): '&gt;',
052|     ord('"'): '&quot;',
053| }
054| s1 = s.translate(html_string_map)
055| 
056| class html_string (dict):
057|     '''Prepare string for HTML.'''
058|     def __init__ (self):
059|         '''Initialize instance with special chars.'''
060|         super().__init__()
061|         self[ord('&')] = '&amp;'
062|         self[ord('<')] = '&lt;'
063|         self[ord('>')] = '&gt;'
064|         self[ord('"')] = '&quot;'
065| 
066| cm = html_string()
067| s2 = s.translate(cm)
068| 
069| #:code::
070| UCA,UCZ = ord('A'),ord('Z')
071| LCA,LCZ = ord('a'),ord('z')
072| DIG0,DIG9 = ord('0'),ord('9')
073| 
074| s_in = 'Now is the time for a pretty good party!'
075| 
076| # Version 1: subclass of dict
077| class rot13_string (dict):
078|     '''ROT13 encoder, str.translate style. (subclass)'''
079|     def __getitem__ (self, key):
080|         '''Convert alphnums and digits.'''
081|         if UCA <= key <= UCZ: return UCA+(((key-UCA)+13)%26)
082|         if LCA <= key <= LCZ: return LCA+(((key-LCA)+13)%26)
083|         if DIG0 <= key <= DIG9: return DIG0+(((key-DIG0)+5)%10)
084|         return super().__getitem__(key)
085| 
086| rot13 = rot13_string()
087| s_out = s_in.translate(rot13)
088| s_txt = s_out.translate(rot13)
089| print(s_in)
090| print(s_out)
091| print(s_txt)
092| print()
093| 
094| # Version 2: class implementing __getitem__
095| class rot13_object:
096|     '''ROT13 encoder, str.translate style. (object)'''
097|     def __getitem__ (self, key):
098|         '''Convert alphnums and digits.'''
099|         if UCA <= key <= UCZ: return UCA+(((key-UCA)+13)%26)
100|         if LCA <= key <= LCZ: return LCA+(((key-LCA)+13)%26)
101|         if DIG0 <= key <= DIG9: return DIG0+(((key-DIG0)+5)%10)
102|         return key
103| 
104| rot13 = rot13_object()
105| s_out = s_in.translate(rot13)
106| s_txt = s_out.translate(rot13)
107| print(s_in)
108| print(s_out)
109| print(s_txt)
110| print()
111| 
112| #:code::
113| SPC = ord(' ')
114| UCA,UCZ = ord('A'),ord('Z')
115| LCA,LCZ = ord('a'),ord('z')
116| DIG0,DIG9 = ord('0'),ord('9')
117| 
118| class url_string (dict):
119|     '''Translate for URL: Accept alnums (others to %## hex).'''
120|     def __init__ (self):
121|         '''Initialize instance with special chars.'''
122|         super().__init__()
123|         self[SPC] = '+'
124| 
125|     def __getitem__ (self, key):
126|         '''Explicitly pass alnums. Delegate others.'''
127|         if UCA <= key <= UCZ: return key
128|         if LCA <= key <= LCZ: return key
129|         if DIG0 <= key <= DIG9: return key
130|         return super().__getitem__(key)
131| 
132|     def __missing__ (self, key):
133|         '''Convert non-special chars to %## hex.'''
134|         return '%%%02X' % key
135| 
136| #:code::
137| TAB = ord('\t')
138| EOL = ord('\n')
139| SPC = ord(' ')
140| UCA,UCZ = ord('A'),ord('Z')
141| LCA,LCZ = ord('a'),ord('z')
142| DIG0,DIG9 = ord('0'),ord('9')
143| 
144| class basic_text_string (dict):
145|     '''Convert LC=>UC; Pass digits; ^C=>hex; Else skip.'''
146|     def __init__ (self):
147|         '''Initialize instance with special chars.'''
148|         super().__init__()
149|         self[TAB] = '<TAB>'
150|         self[EOL] = '<NL>'
151|         self[SPC] = '_'
152| 
153|     def __missing__ (self, key):
154|         '''Handle everything else here.'''
155|         if UCA <= key <= UCZ: return key+32
156|         if LCA <= key <= LCZ: return key
157|         if DIG0 <= key <= DIG9: return key
158|         if 0 <= key < SPC:
159|             return ('<%02x>' % key)
160|         return None
161| 
162| s = '''\
162| Samantha Ann Bear
162| 13924 Schulte Way
162| \tApt. 2402
162| Forest City, CA 92508
162| [code:QRTD8945-2740-21]
162| '''

163| cmap = basic_text_string()
164| print(s)
165| print(s.translate(cmap))
166| print()
167| 
168| #:code::
169| class telegraph_string (dict):
170|     '''Pass spaces; UC=>LC; digits,TAB,EOL==>words.'''
171|     def __init__ (self):
172|         '''Initialize character translations.'''
173|         super().__init__()
174|         self[SPC] = SPC
175|         self[TAB] = ' TAB '
176|         self[EOL] = ' || '
177|         self[ord('0')] = ' ZERO '
178|         self[ord('1')] = ' ONE '
179|         self[ord('2')] = ' TWO '
180|         self[ord('3')] = ' THREE '
181|         self[ord('4')] = ' FOUR '
182|         self[ord('5')] = ' FIVE '
183|         self[ord('6')] = ' SIX '
184|         self[ord('7')] = ' SEVEN '
185|         self[ord('8')] = ' EIGHT '
186|         self[ord('9')] = ' NINE '
187|         self[ord('.')] = ' STOP '
188|         self[ord(',')] = ' COMMA '
189|         self[ord(':')] = ' COLON '
190| 
191|     def __missing__ (self, key):
192|         if UCA <= key <= UCZ: return key
193|         if LCA <= key <= LCZ: return key-32
194|         return None
195| 
196| cmap = telegraph_string()
197| print(s)
198| print(s.translate(cmap))
199| print()
200| 
201| #:end:code::
202|