0

In Python, I have a string of the form "1343214324" - all characters are either "1", "2", "3", or "4". I am trying to replace all instances of "1" with "3", all instances of "3" with "1", all instances of "2" with "4", and all instances of "4" with "2". If I just used replace, I would get a string of all "1"s and "2"s. In the above, it should return "3121432142".

Right now, I am simply iterating through the characters in the string and appending to another string.

newString = ""
for ch in string:
    ch = string[j]
    if ch == "1":
        newString += "3"
    elif ch == "2":
        newString += "4"
    elif ch == "3":
        newString += "1"
    else:
        newString += "2"

Although this works, I feel like it is not very pythonic and could even be more efficient. Is there a more pythonic way of doing the above?

Varun Vejalla
  • 183
  • 1
  • 8

1 Answers1

0

Use dict with str.join:

s = "1343214324"
d = {'1': '3', '3': '1', '2': '4', '4': '2'}
''.join([d[i] for i in s])

Output:

'3121432142'
Chris
  • 29,127
  • 3
  • 28
  • 51