Assume that we have a string like:XYYX. I want to get YXXY.How do I do that in python?
couldnt think of anything
CodePudding user response:
str = str.replace("X", "*")
str = str.replace("Y", "X")
str = str.replace("*", "Y")
CodePudding user response:
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
CodePudding user response:
As Chris suggested:
string = "XYYX"
table = str.maketrans("XY", "YX")
string.translate(table)
'YXXY'