Home > python > replace characters in a string

replace characters in a string

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 .

Advertisements
Categories: python Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: