Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find last occurence of multiple characters in a string in Python

Tags:

python

string

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

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

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

I would want a function that returns the index of the last occurence of {, [, or { similar to

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

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

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

seems clunky and not Pythonic.

like image 282
capt-calculator Avatar asked Aug 11 '15 19:08

capt-calculator


Video Answer


3 Answers

You can use generator expression to do this in a Pythonic way.

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

This iterates through the list/tuple of characters that you want to check and uses rfind() on them, groups those values together, and then returns the maximum value.

like image 83
michaelpri Avatar answered Oct 09 '22 17:10

michaelpri


This is pretty concise, and will do the trick.

max(map(test_string.rfind, '([{'))
like image 34
pzp Avatar answered Oct 09 '22 18:10

pzp


You can use reversed to start at the end of the string getting the first match, using the length of the string -1 - the index i to get the index counting from the start, doing at worst a single pass over the string:

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 a lot more efficient if you a large amount of substrings to search for than doing an O(n) rfind for every substring you want to match and then getting the max of all those

like image 1
Padraic Cunningham Avatar answered Oct 09 '22 17:10

Padraic Cunningham