Home > Software engineering >  how to swap all occurrences of char1 and char2 in a string in python
how to swap all occurrences of char1 and char2 in a string in python

Time:07-09

Let's say that I have this string

"I am very good at coding" 

and I want to replace all occurrences of the char "o" with "a" while simultaneously replacing every "a" with "o" so that I get

"I om very gaad ot cading" 

everything I found on Google doesn't really work for me btw, it's a very long string

CodePudding user response:

The easiest I found was to use replace 3 times.

string.replace('o', '$$')
string.replace('a', 'o')
string.replace('$$', 'a')

CodePudding user response:

You could use this trivial solution

def swap_chars(string, ch1, ch2):
    if ch1 == ch2: return string
    str_list = []
    for char in string:
        if char == ch1:
            str_list.append(ch2)
        elif char == ch2:
            str_list.append(ch1)
        else:
            str_list.append(char)
    return ''.join(str_list)

print(swap_chars("I am very good at coding", 'o', 'a'))

CodePudding user response:

Since there is no one use the translation as @Barmar suggested earlier, I thought it's good to put here for reference and completeness. Credit should go to him.

# string = 'your string ..... '
>>> mapping = {ch: ord(ch) for ch in 'aeiou'}
>>> mapping            # mapping table needed
{'a': 97, 'e': 101, 'i': 105, 'o': 111, 'u': 117}
>>> mapping = {97: 111, 111: 97}
>>> string.translate(mapping)
'I om very gaad ot cading'
>>> 

CodePudding user response:

text = "I am very good at coding"

uniqueChars = set(text.lower().replace(" ", "")) # 'acdegimnortvy'

import itertools as it

# find all combinations witouth repetitions of 2 chars in uniqueChars
combin = it.combinations(uniqueChars, 2)

#do all translations of the text
translations = []
import string

for letters in combin:
    pairChars="".join(letters)
    transTable = text.maketrans(pairChars, pairChars[::-1])
    translations.append(text.lower().translate(transTable).capitalize())

# translate string
print(translations)

>>>['I cm very good ct aoding', 'C am very good at iodcng', 'I am verc good at yoding', 'I am very gccd at ocding', 'I am cery good at voding', 'I ac very good at moding', 'I am vcry good at eoding', 'I am very good ac toding', 'I am very cood at godinc', 'I am very gooc at docing', 'I am vecy good at roding', 'I am very good at nodicg', 'A im very good it codang', 'I ym vera good yt coding', 'I om very gaad ot cading', 'I vm aery good vt coding', 'I ma very good mt coding', 'I em vary good et coding', 'I tm very good ta coding', 'I gm very aood gt codina', 'I dm very gooa dt coaing', 'I rm veay good rt coding', 'I nm very good nt codiag', 'Y am veri good at codyng', 'O am very giid at cidong', 'V am iery good at codvng', 'M ai very good at codmng', 'E am viry good at codeng', 'T am very good ai codtng', 'G am very iood at codgni', 'D am very gooi at coidng', 'R am veiy good at codrng', 'N am very good at codnig', 'I am vero gyyd at cyding', 'I am yerv good at coding', 'I ay verm good at coding', 'I am vyre good at coding', 'I am vert good ay coding', 'I am verg yood at codiny', 'I am verd gooy at coying', 'I am veyr good at coding', 'I am vern good at codiyg', 'I am oery gvvd at cvding', 'I ao very gmmd at cmding', 'I am vory geed at ceding', 'I am very gttd ao ctding', 'I am very oggd at cgdino', 'I am very gddo at cdoing', 'I am veoy grrd at crding', 'I am very gnnd at cndiog', 'I av mery good at coding', 'I am evry good at coding', 'I am tery good av coding', 'I am gery vood at codinv', 'I am dery goov at coving', 'I am revy good at coding', 'I am nery good at codivg', 'I ae vmry good at coding', 'I at very good am coding', 'I ag very mood at codinm', 'I ad very goom at coming', 'I ar vemy good at coding', 'I an very good at codimg', 'I am vtry good ae coding', 'I am vgry eood at codine', 'I am vdry gooe at coeing', 'I am vrey good at coding', 'I am vnry good at codieg', 'I am very tood ag codint', 'I am very goot ad coting', 'I am vety good ar coding', 'I am very good an coditg', 'I am very doog at cogind', 'I am vegy rood at codinr', 'I am very nood at codign', 'I am vedy goor at coring', 'I am very goon at conidg', 'I am veny good at codirg']

CodePudding user response:

It was interesting to compare two methods in Python with no fancy method.
One is to use translate method and the other is to use plain dict
Apparently, using 'translate' is much superior.
here is a code to test:

import timeit

my_str = "I am very good at coding"


def replace_ao_with_translate(string):
    dic = {'a': 'o', 'A': 'O', 'o': 'a', 'O': 'A'}
    table = string.maketrans(dic)
    return string.translate(table)


def replace_ao_with_dic(string):
    dic = {'a': 'o', 'A': 'O', 'o': 'a', 'O': 'A'}
    new_string = []
    for char in string:
        if char in dic:
            new_string.append(dic[char])
        else:
            new_string.append(char)
    return ''.join(new_string)


print(replace_ao_with_translate(my_str))
print(replace_ao_with_dic(my_str))
print(timeit.timeit("replace_ao_with_translate(my_str)", globals=globals()))
print(timeit.timeit("replace_ao_with_dic(my_str)", globals=globals()))

The replace_ao_with_translate is clearly faster.

  • Related