Is there a function in python to replace characters in a string and vice-versa?

The last part of the question is what’s throwing me off. I need to do this in one line with List Comprehension and so far I’ve tried this:

def Function(string):
    new_string = ''.join([string.replace('X','Y').replace('Y','X')])
    return new_string

The output for this is always going to be ‘X’ regardless of whether my string argument is ‘X’ or ‘Y’ because of the way I’m using .replace(), but I need it replace either or and I’m not sure how to do that in just one line. What are your thoughts?

>Solution :

In one line, you could use a double nested ternary expression to swap X and Y

def f(string):
   return "".join(["X" if c=="Y" else ("Y" if c=="X" else c) for c in string])

Another approach with a dictionary

"".join({"X":"Y","Y":"X"}.get(c,c) for c in string)

The second approach may appear faster but the catch is, because of the one-liner requirement, the dictionary is created at each iteration. So to be faster, the dictionary should be stored in a variable first.

In one line (this is ludicrious, though)

def f(string):
    return "".join(d.get(c,c) for d in ({"X":"Y","Y":"X"},) for c in string)

Leave a Reply