Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a string by swapping multiple letters

Say I have a very long string like 'ABCEEEEEEDEDAAA......' but it is only made up of five letters. Say I want all 'A' to be 'D' and vice versa, and same to 'B' and 'C'(an example would be nucleotides in DNA....). The example, after modification, would be 'DCBEEEEEEAEADDD....... I realized that code like string.replace('A','D').replace('D','A') just wouldn't work. And I would like to know what is the fastest approach since the other approach that comes up to me is just finding every index, which looks a little bit complicated.

like image 457
Peter Jiang Avatar asked Mar 08 '23 15:03

Peter Jiang


1 Answers

Since the requirement is for multiple replacements, its better to use str.translate() by creating a mapping table first using str.maketranslate().

Example using a shortened version of your sample where 'A'->'D' , 'D'->'A' , 'B'->'C' , 'C'->'B'

>>> s = 'ABCEEEEEEDEDAAA'
>>> orig = 'ABCD'
>>> rep = 'DCBA'
>>> trans_table = str.maketrans(orig,rep)

>>> s.translate(trans_table)
=> 'DCBEEEEEEAEADDD'

Another method would be to make use of str.replace function, but which would require more amount of code lines for the same functionality. It can be done by using a temporary placeholder for replacements.

Example : suppose for just 'A'->'B' and 'B'->'A'

>>> s = 'ABBA'
>>> s = s.replace('A','$')
#'$BB$'
>>> s = s.replace('B','A')
#'$AA$'
>>> s = s.replace('$','B')
>>> s
=> 'BAAB' 

Here $ is used as placeholder. As you can see, this becomes tiresome with large replacement requirements.

NOTE : in the above method, the placeholders should be unique too and should not be already present in the string.

like image 51
Kaushik NP Avatar answered Mar 16 '23 16:03

Kaushik NP