Search code examples
pythonstringreplacetoken

Python - replacing a pattern in a string


I have strings which contains certain words with the following form:

'something1__something2__need'

for example here is a full string with those words:

'bla__wewe__23,sad__fd__sas po__oop__retq2'

I want to extract a new string with only the last sub-word in each word in the string, meaning that my first example turns into 'need' and the second into '23,sas retq2'. Possible delimiters are spaces and commas. Should be without loops if possible.


Solution

  • Using Regex.

    Demo:

    import re
    
    s = ['something1__something2__need', 'bla__wewe__23,sad__fd__sas po__oop__retq2']
    for i in s:
        val = re.split(r"([,\s])", i)     #Split by space, comma
        print("".join(j.split("__")[-1] for j in val))    #Split by __ and join by last element in list.
    

    Output:

    need
    23,sas retq2