How would I find the last occurrence of a character in a string?
string = "abcd}def}" string = string.find('}',last) # Want something like this
The rfind() method finds the last occurrence of the specified value. The rfind() method returns -1 if the value is not found. The rfind() method is almost the same as the rindex() method.
Here we illustrate the most reliable way to get the last occurrences of the string items by using the string rindex() method. The rindex() command returns the last existence of the substring or character if present in the Python string.
strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .
rindex() method is similar to rfind() method for strings. The only difference is that rfind() returns -1 if the substring is not found, whereas rindex() throws an exception.
You can use rfind
:
>>> "abcd}def}".rfind('}') 8
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With