简体   繁体   中英

How to remove last occurrence of a substring from a picece of string?

I have a string like this- "DEMO_ANNO_COUNT_ANNO_1" and "DEMO_ANNO_COUNT_ANNO_25"

and I need a generalized method to remove the last _ANNO and whatever following that, so that I have "DEMO_ANNO_COUNT" on both the cases

You can use rsplit to split the string from the right once and retrieve the first element of the result:

In [1]: "DEMO_ANNO_COUNT_ANNO_1".rsplit("_ANNO", 1)[0]                          
Out[1]: 'DEMO_ANNO_COUNT'

In [2]: "DEMO_ANNO_COUNT_ANNO_25".rsplit("_ANNO", 1)[0]                         
Out[2]: 'DEMO_ANNO_COUNT'

In [3]: "DEMO_ANNO_COUNT_ANNO_25".rsplit("_ANNO", 1)                            
Out[3]: ['DEMO_ANNO_COUNT', '_25']
# The first element of that will always be
# whatever was before the last "_ANNO"

Same thing as my comment, but in Python code I am reversing the string. Finding index of reversed pattern and then take slice of original string until len(ONNA_)+index characters remain

def remove_upto_last_pattern(word, pattern):
    reversed_word = word[::-1]
    pattern = pattern[::-1]
    pattern_index = reversed_word.index(pattern)
    return word[:-1*(pattern_index+len(pattern))]


if __name__ == '__main__':
    print(remove_upto_last_pattern('DEMO_ANNO_COUNT_ANNO_1', '_ANNO'))
    print(remove_upto_last_pattern('DEMO_ANNO_COUNT_ANNO_25', '_ANNO'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM