Archive

Posts Tagged ‘translate’

remove punctuations from a text

February 5, 2017 Leave a comment

Problem
You have a text and you want to remove punctuations from it. Example:

in:
"Hello! It is time to remove punctuations. It is easy, you will see."

out:
"Hello It is time to remove punctuations It is easy you will see"

Solution
Let’s see a Python 3 solution:

>>> import string
>>> tr = str.maketrans("", "", string.punctuation)
>>> s = "Hello! It is time to remove punctuations. It is easy, you will see."
>>> s.translate(tr)
'Hello Its time to remove punctuations Its easy youll see'

Docs: str.maketrans(), str.translate().

Categories: python Tags: , ,

replace characters in a string

December 16, 2016 Leave a comment

Problem
You have a string, and you want to replace some characters to some other characters. The first thing that pops into mind is “replace”:

>>> s = "ebbe"
>>> s.replace('e', 'a')
'abba'

But what if you need to replace 1s to 0s and 0s to 1s in “100”? The result, in this case, should be “011”.

Solution
A straightforward solution would be to use a “temporary variable”, in this case a third kind of character:

>>> s = "100"
>>> s.replace('1', 't').replace('0', '1').replace('t', '0')
'011'

A more elegant way is to use “translate”:

>>> s = "100"
>>> s.translate(str.maketrans('01', '10'))
'011'

More info here: https://docs.python.org/3/library/stdtypes.html#str.maketrans .

Categories: python Tags: , ,