Python Forum
Explaining "translate" method
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Explaining "translate" method
#5
If it's about string method translate maybe following examples can help to understand.

Task: we want to remove numbers from string using translate method

We create dictionary to replace numbers (by mapping numbers to None) and try to use translate:

>>> dict.fromkeys('0123456789')
{'0': None, '1': None, '2': None, '3': None, '4': None, '5': None, '6': None, '7': None, '8': None, '9': None}
>>> '2 for 1'.translate(dict.fromkeys('0123456789'))
'2 for 1'
Nothing happened. Why? .translate expects Unicode code points (integers) as keys.

If we use maketrans mentioned in documentation:

>>> remove_numbers = str.maketrans(dict.fromkeys('0123456789'))
>>> remove_numbers
{48: None, 49: None, 50: None, 51: None, 52: None, 53: None, 54: None, 55: None, 56: None, 57: None}
We see that it automagically replaced strings with Unicode code points. If we try translate with this we see expected result:

>>> '2 for 1'.translate(remove_numbers)
' for '                                   # we observe spaces before and after 'for' as they were
>>> '2 for 1'.translate(remove_numbers).strip()
'for'                                     # we can strip spaces from beginning and end
We can make translation dictionary by ourselves, not using maketrans method (like in example #2). In spoken language: 'give me key as unicode code point for character and value as None for every character in string':

>>> {ord(i): None for i in " ',"}
{32: None, 39: None, 44: None}
>>> {ord(i): None for i in '0123456789'}
{48: None, 49: None, 50: None, 51: None, 52: None, 53: None, 54: None, 55: None, 56: None, 57: None}
>>> '2 for 1'.translate({ord(i): None for i in '0123456789'})
' for '
If one is sufficiently proficient in Unicode then translation dictionary can be created like:

>>> {i: None for i in range(48,58)}
{48: None, 49: None, 50: None, 51: None, 52: None, 53: None, 54: None, 55: None, 56: None, 57: None}
>>> dict.fromkeys(range(48,58))
{48: None, 49: None, 50: None, 51: None, 52: None, 53: None, 54: None, 55: None, 56: None, 57: None}
Removing characters can be combined with replacing as well:

>>> mapping = str.maketrans({**dict.fromkeys('0123456789'), **{'f': 'F'}}) 
>>> mapping
{48: None, 49: None, 50: None, 51: None, 52: None, 53: None, 54: None, 55: None, 56: None, 57: None, 102: 'F'}
>>> '2 for 1'.translate(mapping)
' For '
Or only replacing (one can replace characters with word):

>>> nums_to_words = str.maketrans(dict(zip('0123456789', 'zero one two three four five six seven eight nine'.split())))
>>> nums_to_words
{48: 'zero', 49: 'one', 50: 'two', 51: 'three', 52: 'four', 53: 'five', 54: 'six', 55: 'seven', 56: 'eight', 57: 'nine'}
>>> '2 for 1'.translate(nums_to_words)                                    
'two for one'
You can translate one code point to string but not string (several code points) like '10' to some replacement value (like string ten):

>>> ord('10')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 2 found
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
Explaining "translate" method - by lummers - Jan-11-2020, 07:45 AM
RE: Explaining "translate" method - by perfringo - Jan-11-2020, 08:33 AM
RE: Explaining "translate" method - by Gribouillis - Jan-11-2020, 09:08 AM
RE: Explaining "translate" method - by ndc85430 - Jan-12-2020, 05:33 PM
RE: Explaining "translate" method - by perfringo - Jan-13-2020, 06:31 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  for loop and if translate from R in Python Joey21 3 4,034 Feb-06-2018, 02:16 PM
Last Post: sparkz_alot
  Need help explaining what the variables do in my code. BurnedChipotle 6 6,326 Jan-30-2017, 10:48 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020