5

Lets say I have this string "abcd"

Now I want to replace all 'a's with a 'd' and I want to replace all 'd's with an 'a'. The problem is that string.replace does not work in this situation.

"abcd".replace('a','d').replace('d','a')

abca

Expected output is "dbca"

How would I acheive this?

John Smith
  • 347
  • 1
  • 11

3 Answers3

5

You could use .translate().

Return a copy of the string in which each character has been mapped through the given translation table.

https://docs.python.org/3/library/stdtypes.html#str.translate

Example:

>>> "abcd".translate(str.maketrans("ad","da"))
'dbca'
Loocid
  • 6,112
  • 1
  • 24
  • 42
0

You can use a list comprehension to switch the values that you want

x = "abcd"
''.join(['d' if i == 'a' else 'a' if i == 'd' else i for i in x])

'dbca'


Without a list

x = "abcd"
''.join('d' if i == 'a' else 'a' if i == 'd' else i for i in x)

'dbca'


Timing

In [1]: x = "abcd"*10000000

In [2]: %timeit ''.join('d' if i == 'a' else 'a' if i == 'd' else i for i in x)
5.78 s ± 152 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit ''.join(['d' if i == 'a' else 'a' if i == 'd' else i for i in x])
4.49 s ± 157 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

It turns out the list comprehension is slightly faster.

user3483203
  • 50,081
  • 9
  • 65
  • 94
JahKnows
  • 2,618
  • 3
  • 22
  • 37
  • You don't need the list, you can just use a comprehension. Creating a list will always hurt performance – user3483203 Apr 06 '18 at 04:11
  • @chrisz what do you mean by "a comprehension" here? List comprehensions create lists – juanpa.arrivillaga Apr 06 '18 at 04:18
  • @juanpa.arrivillaga he doesn't need the brackets, they hurt performance. `''.join('d' if i == 'a' else 'a' if i == 'd' else i for i in x)` works perfectly fine. I should have said, "you can just use a generator" – user3483203 Apr 06 '18 at 04:19
  • I may be completely wrong about this. I just timed with a list and a generator and the list was twice as fast. hmm... – user3483203 Apr 06 '18 at 04:20
  • 1
    @JahKnows I was indeed wrong, list is better here. https://stackoverflow.com/questions/37782066/list-vs-generator-comprehension-speed-with-join-function My apologies – user3483203 Apr 06 '18 at 04:23
  • 1
    No, actually, generally unless your list would be very large a list comprehension will beat or match a *generator expression*. In the particular case of passing to `str.join` a list is created under the hood anyway. – juanpa.arrivillaga Apr 06 '18 at 04:46
0

you can try python replace recipe :

string_word="abcd"

data=list(string_word)
replace_index=list({j:i for j,i in enumerate(data) if i=='a' or i=='d'}.keys())

data[replace_index[0]],data[replace_index[1]]=data[replace_index[1]],data[replace_index[0]]

print("".join(data))

output:

dbca
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88