python字符在列表中的位置_Python编程题17--字符串在另一个字符串中的位置

题目

给定字符串A和字符串B,请检测字符串A是否在字符串B中,如果存在则返回字符串B中每次出现字符串A的起始位置,否则返回 -1 。

例如:

给定一个字符串:GBRRGBRGG,另一个字符串:RG

那么字符串 RG 在 GBRRGBRGG 中出现的位置为 3,6

实现思路1

设置一个列表,用于存储结果,分别计算出长字符串s1和短字符串s2的长度:len1、len2

对长字符串s1进行遍历,遍历过程当索引下标到 len1 - len2 时,结束遍历

遍历过程,对长字符串s1进行切片操作,起始索引为 i ,结束索引为 i + len2

如果切片得到的结果恰等于 s2 ,那就说明 s2 在 s1 出现了,此时把本次出现的起始位置 i 添加到结果列表中

最后,判断结果列表是否为空,不为空则返回结果,否则返回 -1

代码实现

def index_of_str(s1, s2):

res = []

len1 = len(s1)

len2 = len(s2)

if s1 == "" or s2 == "":

return -1

for i in range(len1 - len2 + 1):

if s1[i] == s2[0] and s1[i:i+len2] == s2:

res.append(i)

return res if res else -1

str1 = "cdembccdefacddelhpzmrtcdeqpjcde"

str2 = "cde"

print("字符串 {} 在另一个字符串 {} 中出现的位置:{} ".format(str2, str1, index_of_str(str1, str2)))

实现思路2

设置一个列表,用于存储结果

设置一个变量index,用于表示短字符串s2在长字符串s1中出现的位置,默认为 0

通过短字符串s2,对长字符串s1进行分割操作,得到的结果存储到 split_list

对split_list进行遍历,遍历完倒数第二个元素时,结束遍历

遍历过程,把 index 添加到结果列表中

最后,判断结果列表是否为空,不为空则返回结果,否则返回 -1

注意:split() 分割操作时,如果所指定分割串不在字符串中,那么会返回字符串本身。

代码实现

def index_of_str(s1, s2):

res = []

index = 0

if s1 == "" or s2 == "":

return -1

split_list = s1.split(s2)

for i in range(len(split_list) - 1):

index += len(split_list[i])

res.append(index)

index += len(s2)

return res if res else -1

str1 = "cdembccdefacddelhpzmrtcdeqpjcde"

str2 = "cde"

print("字符串 {} 在另一个字符串 {} 中出现的位置:{} ".format(str2, str1, index_of_str(str1, str2)))

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值