Find last occurrence of multiple characters in a string in Python

I would like to find the last occurrence of the number of characters in a string.

str.rfind () will give the index of the last occurrence of one character in the string, but I need the index of the last occurrence of any of several characters. For example, if I had a line:

test_string = '([2+2])-[3+4])' 

I need a function that returns the index of the last occurrence of {, [, or {similarly

 test_string.rfind('(', '[', '{') 

Which ideally will return 8. What is the best way to do this?

 max(test_string.rfind('('), test_string.rfind('['), test_string.rfind('{')) 

seems awkward, not Pythonic.

+4
source share
4 answers

You can use the generator expression for this in Pythonic.

 max(test_string.rfind(i) for i in "([{") 

This is repeated through the list / tuple of characters you want to test, and uses rfind() , groups these values โ€‹โ€‹together and then returns the maximum value.

+5
source

You can use reverseed to start at the end of the line that gets the first match, using the length of the string -1 - index i to get the index counted from the very beginning, making in the worst case one pass of the line:

 test_string = '([2+2])-[3+4])' st = {"[", "(", "{"} print(next((len(test_string) - 1 - i for i, s in enumerate(reversed(test_string)) if s in st),-1)) 8 

If there is no match, you will get -1 as the default value. This is much more efficient if you can find a large number of substrings than do O(n) rfind for each substring you want to match, and then get the maximum of all of these

+1
source
 >>> def last_of_many(string, findees): ... return max(string.rfind(s) for s in findees) ... >>> test_string = '([2+2])-[3+4])' >>> last_of_many(test_string, '([{') 8 >>> last_of_many(test_string, ['+4', '+2']) 10 >>> 
0
source

This is pretty brief and will do the trick.

 max(map(test_string.rfind, '([{')) 
0
source

All Articles