Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading