Find index of last occurrence of a substring in a string
Use .rfind()
:
>>> s = 'hello'
>>> s.rfind('l')
3
Also don't use str
as variable name or you'll shadow the built-in str()
. Finding last index of a substring in a string
Add the length of the substring to the index of the substring.
def find_substring_index(string, substring):
return string.index(substring) + len(substring) - 1
Subtract 1 because you want the index of the last character, otherwise it will return the index just past the match. Find index of last occurrence of a sub-string using T-SQL
You are limited to small list of functions for text data type.
All I can suggest is start with PATINDEX
, but work backwards from DATALENGTH-1, DATALENGTH-2, DATALENGTH-3
etc until you get a result or end up at zero (DATALENGTH-DATALENGTH)
This really is something that SQL Server 2000
simply can't handle.
Edit for other answers : REVERSE is not on the list of functions that can be used with text data in SQL Server 2000
Find last occurrence of character in string Python
You can use rfind
:
>>> "abcd}def}".rfind('}')
8
Trying to get the last occurrence of a substring in string using recursion in python
It's not obvious that your strDist
function ever converges toward a base case. Using global
in a recursive function almost always makes it harder to debug and reason about; odds are good that dist
is winding up with a value you don't expect at some point, and that's what's leading to infinite recursion.
Using find
(which is an iterative function) in your recursive function sort of defeats the purpose anyway, since as pointed out, if you're going to use find
to find the leftmost occurrence, you could just also use rfind
to find the rightmost occurence, and then you're done without having to do any recursion at all.
A purely recursive (also inefficient) solution would look more like:
def str_dist(message, substr):
if len(message) < len(substr):
return -1
if message.startswith(substr) and message.endswith(substr):
return len(message)
return max(str_dist(message[1:], substr), str_dist(message[:-1], substr))
The above function is purely recursive in that it doesn't do any iteration over message
within a given function call (note that startswith
and endswith
are both iterative over substr
; you could write recursive versions of those as well if you really wanted to) and it passes all of your tests.It has two base cases:
- There's no valid answer if
message
is shorter thansubstr
. (Some form of "too small" base case is needed to prevent infinite recursion on empty strings -- you could make the empty string the base case if you wanted to make this check simpler.) - The answer is
len(message)
ifmessage
itself meets the condition of starting and ending withsubstr
.
message[1:]
or message[:-1]
. Get index of last occurence of matched string?
let text = 'Hello, this is a test. foo'; let lastChar = [...text.matchAll(/[\.,;]/g)].pop().indexconsole.log(lastChar)
Finding the index of occurrence before the last occurrence of a string
You should use indexOf
twice.
int lastOccurence = str.lastIndexOf('+'); // This will give you last occurence of + in your string
if (lastOccurence > -1) {
int secondLastOccurence = str.lastIndexOf('+', lastOccurence -1);
}
How to find all occurrences of a substring?
There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:
import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]
If you want to find overlapping matches, lookahead will do that:[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]
If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]
re.finditer
returns a generator, so you could change the []
in the above to ()
to get a generator instead of a list which will be more efficient if you're only iterating through the results once.
Related Topics
Does Conda Replace the Need for Virtualenv
How to Have Shared Log Files Under Windows
In Python, What Happens When You Import Inside of a Function
Download Image File from the HTML Page Source
Is There a Simple Process-Based Parallel Map for Python
Using Configparser to Read a File Without Section Name
Running a Command as a Super User from a Python Script
Python - Email Header Decoding Utf-8
Pandas Interpolate Within a Groupby
Python Progress Bar and Downloads
Numpy 1.21.2 May Not Yet Support Python 3.10
Python - Datetime with Timezone to Epoch
Selecting Columns from Pandas Multiindex
What Is the Official "Preferred" Way to Install Pip and Virtualenv Systemwide
How to Flatten a Pandas Dataframe with Some Columns as JSON
How to Add Trendline in Python Matplotlib Dot (Scatter) Graphs