i_love_whiteboards
i_love_whiteboards

Reputation: 59

swap/replace chars in a string

Im trying to get a string with 4 different character values, where I want to swap two characters around with each other and the other two characters around with each other

I have this so far, but the replace method I am using is replacing the characters along the way making the outcome incorrect.

my code is like this:

s = 'ABBDCA'

# printing original lists
print("The original list is : " + str(s))
  
# Swap elements in String list
# using replace() + list comprehension
res = [sub.replace('B', 'A').replace('D', 'C').replace('A', 'B').replace('C', 'D') for sub in s]
  
# printing result 
print ("List after performing character swaps : " + str(res))

and my outcome is

The original list is : ABBDCA
List after performing character swaps : ['B', 'B', 'B', 'D', 'D', 'B']

But the outcome I am trying to get is:

BAACDB

So swap A & B around in the string and C & D around too.

Upvotes: 0

Views: 851

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54645

Can you see why this happens? After you replace all the Bs with As, now there's a lot more As to be converted back to Bs. You'll need to do this character by character:

s = 'ABBDCA'
xlate = {'A':'B','B':'A','C':'D','D':'C'}
res = ''.join(xlate[c] for c in s)

Upvotes: 3

Related Questions