子串出现次数 [英] Substring Occurrences

查看:29
本文介绍了子串出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有一个问题,我真的不知道从哪里开始

I have a question here and I really don't know where to start on it short of

s1.find(s2)

任何帮助将不胜感激.

变量 s1 和 s2 指的是 strs.表达式 s1.find(s2) 返回 s1 中第一次出现 s2 的索引.表达式 s1.find(s2, 5) 返回 s1 中第一次出现 s2 的索引,从 s1 中的索引 5 开始.(查看帮助(str.find)了解更多信息)

Variables s1 and s2 refer to strs. The expression s1.find(s2) returns the index of the first occurrence of s2 in s1. The expression s1.find(s2, 5) returns the index of the first occurrence of s2 in s1, starting at index 5 within s1. (See help(str.find) for more info)

编写一个表达式,生成 s1 中第二次出现 s2 的索引.如果 s2 在 s1 中没有出现两次,则表达式应产生 -1.与 str.count 不同,您应该允许 s2 重叠出现.

Write an expression that produces the index of the second occurrence of s2 in s1. If s2 does not occur twice in s1, the expression should produce -1. Unlike str.count, you should allow overlapping occurrences of s2.

例如,如果 s1 是banana"而 s2 是ana",则您的表达式应返回 3.如果 s1 是apple"且 s2 是p",则您的表达式应返回 2.

For example, if s1 is "banana" and s2 is "ana", your expression should return 3. If s1 is "apple" and s2 is "p", your expression should return 2.

您的答案必须是不使用方括号的单个表达式(字符串索引和切片),并且您只能调用方法 str.find 并使用算术运算符(+、- 等).

Your answer must be a single expression that does not use square brackets (string indexing and slicing), and you can only call method str.find and use the arithmetic operators (+, -, etc.).

推荐答案

这会打印 3.

s1 = 'banana'
s2 = 'ana'
second_index = s1.find(s2, s1.find(s2)+1)
print(second_index)

这会打印 -1.

s1 = 'bana'
s2 = 'ana'
second_index = s1.find(s2, s1.find(s2)+1)
print(second_index)

因此您可能正在寻找的表达式是 s1.find(s2, s1.find(s2)+1).

Thus the expression you are probably looking for is s1.find(s2, s1.find(s2)+1).

这篇关于子串出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆