python - Strip everything after list of possible delimiters without regex -


i have list of possible delimiters. processing few thousand strings , need strip after 1 of delimiters found. note: there never case when more 1 delimiter in string.

example:

patterns = ['abc', 'def'] example_string = 'hello world abc 123' 

if example_string input in case, output should hello world abc.

i using regex solution, working, use approach doesn't use regex. here's current implementation:

 regex = r'(.*)(' + '|'.join(patterns) + r')(.*)'  example_string= re.sub(regex, r'\1\2', example_string).lstrip() 

i thinking along lines of searching see if 1 of delimiters patterns in string , indexing string position of length of delimiter until end of string.

don't know if way implement that, or if work.

you use find function. here each pattern checked , if found string sliced @ start location of pattern (or end location of pattern adding length of pattern, in example):

    patterns = ['abc', 'def']     example_string = 'hello world abc 123'     pattern in patterns:         location = example_string.find(pattern)         if location >= 0:             example_string = example_string[:location + len(pattern)]             print example_string             break 

Comments