在字符串中寻找目标最后一次出现的位置(python)
2016-12-10 14:26
555 查看
# Define a procedure, find_last, that takes as input
# two strings, a search string and a target string,
# and returns the last position in the search string
# where the target string appears, or -1 if there
# are no occurrences.
#
# Example: find_last('aaaa', 'a') returns 3
# Make sure your procedure has a return statement.
def find_last(string,str):
last_position=-1
while True:
position=string.find(str,last_position+1)
if position==-1:
return last_position
last_position=position
不能返回position,因为position最终可能是-1.我们要返回最后一个目标出现的位置,应该返回last_position,因为他是前一个position的有效位置传递。当position为-1时,last_position保存了上一个position有效位置。这里先定义last_position初值为-1,从第一个(位置为0)字符开始查询,当没有一个目标位置被检索到时直接返回-1,否则从这个目标的下一个位置继续检索,直到position为-1或者检索结束为止。
下面是测试:
#print find_last('aaaa', 'a')
#>>> 3
#print find_last('aaaaa', 'aa')
#>>> 3
#print find_last('aaaa', 'b')
#>>> -1
#print find_last("111111111", "1")
#>>> 8
#print find_last("222222222", "")
#>>> 9
#print find_last("", "3")
#>>> -1
#print find_last("", "")
#>>> 0
# two strings, a search string and a target string,
# and returns the last position in the search string
# where the target string appears, or -1 if there
# are no occurrences.
#
# Example: find_last('aaaa', 'a') returns 3
# Make sure your procedure has a return statement.
def find_last(string,str):
last_position=-1
while True:
position=string.find(str,last_position+1)
if position==-1:
return last_position
last_position=position
不能返回position,因为position最终可能是-1.我们要返回最后一个目标出现的位置,应该返回last_position,因为他是前一个position的有效位置传递。当position为-1时,last_position保存了上一个position有效位置。这里先定义last_position初值为-1,从第一个(位置为0)字符开始查询,当没有一个目标位置被检索到时直接返回-1,否则从这个目标的下一个位置继续检索,直到position为-1或者检索结束为止。
下面是测试:
#print find_last('aaaa', 'a')
#>>> 3
#print find_last('aaaaa', 'aa')
#>>> 3
#print find_last('aaaa', 'b')
#>>> -1
#print find_last("111111111", "1")
#>>> 8
#print find_last("222222222", "")
#>>> 9
#print find_last("", "3")
#>>> -1
#print find_last("", "")
#>>> 0
相关文章推荐
- C语言 编写字符串操作函数strrchr,在字符串中查找目标字符最后一次出现的位置,返回指向这次位置的指针。
- 从一个字符串中寻找某个字符最后出现的位置
- 在大字符串寻找共出现几次子串的位置(KMP算法C写法)
- C# 3.0 Cookbook:一、字符与字符串处理(3):在一个字符串内寻找另一个字符串出现的所有位置
- [置顶] 在字符串中查找一个特定的字符最后一次出现的位置,并返回字符所在位置。
- 截取mysql字符串最后一次出现的位置
- 在大字符串寻找第index次出现子串的位置(BF算法OC写法)
- 查找字符串中要查找的字符串最后一次出现的位置
- php计算最后一次,第一次字符串出现位置
- 【c语言】实现strrchr(查找该字符串最后一次出现的位置)
- # python查找所有子字符串出现的位置
- 如何取得字符在字符串中最后一次出现的位置.
- JavaScript lastIndexOf方法入门实例(计算指定字符在字符串中最后一次出现的位置)
- Python函数——查找字符串第n次出现的位置
- Java查找指定字符串第一次或最后一次出现的位置
- 从源字符串中查找最后一次出现的目标字符串
- 如何找到二分查找中目标元素第一次出现和最后一次出现的位置
- python 字符串第n次出现的位置
- JavaScript lastIndexOf方法入门实例(计算指定字符在字符串中最后一次出现的位置)
- sql怎么取某个字符串最后一次出现的位置后面的字符串