how to convert X to Y and Y to X at the same time in a string in python

Question:

Assume that we have a string like:XYYX. I want to get YXXY.How do I do that in python?

couldnt think of anything

Asked By: mlk

||

Answers:

You could just iterate through the string and swap them.

def invert(str):
  newstr = ""
  for i from 0 to len(str):
    if str[i] == 'X':
      newstr += 'Y'
    else:
      newstr += 'X'
  return newstr

Could also just modify the original string.

Edit: I’m assuming this is some kind of from-scratch school assignment

Edit2: My python is a bit rusty, so forgive any syntax errors and treat it as pseudocode if you must; ’tis far from gospel

Answered By: lckcorsi
str = str.replace("X", "*")
str = str.replace("Y", "X")
str = str.replace("*", "Y")
Answered By: kushaan gulati

As Chris suggested:

string = "XYYX"
table = str.maketrans("XY", "YX")
string.translate(table)

'YXXY'
Answered By: SpikyClip
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.