Home > other >  Python, if the end of a RANDOM string in a list is xy, how do I replace it with yx?
Python, if the end of a RANDOM string in a list is xy, how do I replace it with yx?

Time:12-26

For example this is my random list

list = ["asdxy", "abcyx", "asd"]

I want it to be this

list = ["asdyx", "abcyx", "asd"]

CodePudding user response:

You can use the method endswith to check for the suffix of a string object. In your case I would do the transformation of the list as:

my_list = ["asdxy", "abcyx", "asd"]
my_modified_list = [word[:-2]   "yx" if word.endswith("xy") else word for word in my_list]

CodePudding user response:

You can use this to find the end of every word and check if it is 'xy' and replace it:

list_t = ["asdxy", "abcyx", "asd"]

my_list = [s[:-2]   "yx" if s[-2:] == "xy" else s for s in list_t ]

print(my_list)  # prints ["asdyx", "abcyx", "asd"]

CodePudding user response:

Just a hack for fun:

lst = eval(str(lst).replace("xy'", "yx'"))

Two more ways:

import re
lst = [re.sub('xy$', 'yx', s) for s in lst]
lst = [s[:-2]   s[-2:].replace('xy', 'yx') for s in lst]

CodePudding user response:

bringing a howitzer to a knife fight...

import re
my_list = ["asdxy", "abcyx", "asd"]
new_list  = []
for entry in my_list:
    a_match=re.match("^(.*)xy$",entry)
    if a_match:
        new_list.append(a_match.group(1) "yx")
    else:
        new_list.append(entry)

CodePudding user response:

Alternatively, using map:

lst = ["asdxy", "abcyx", "asd"]
lst = [*map(lambda i:(i[:-2] 'yx',i)[i[-2:]!='xy'],lst)]

Or:

lst = ["asdxy", "abcyx", "asd"]
lst = [(i[:-2] 'yx',i)[i[-2:]!='xy'] for i in lst]
  • Related