查找子字符串在给定字符串

时间:2015-07-30 18:16:41

标签: python string python-2.7 find

s = 'This is a bad bad example'
sub = 'bad'

start = 0
count = 0
while True:
    start = s.find(sub,start) + 1
    if start >= 0:
        count = count+1
    else:
        break

print 'The number of times bad appears in the given string is: ' + str(count)

这是我尝试过的。我试图自己调试它,但我无法弄清楚我哪里出错了。我是否错误地使用find()功能?

2 个答案:

答案 0 :(得分:2)

不应该太难,最好的部分是python不需要循环所有东西!

试试这个:

>>> a = "this is a bad bad example"
>>> a.count('bad')
2

a.count(b)返回字符串或列表ba的出现次数。

修改 要解决您的代码:

while True:
    start = s.find(sub,start) + 1
    if start >= 0:
        count = count+1
    else:
        break

您正在使用find(),但是当找不到更多bad时,它将返回-1,然后您将其添加一个(也正确地,由于0 -indexing)然后你检查start >= 0哪个将总是返回true,因为-1(一个错误的结果)将变为0(一个肯定的结果)

试试这个:

start = -1 # start at -1 now, you'll see why...
while True:
    start = s.find(sub,start + 1)
    if start >= 0:
        count = count+1
    else:
        break

因此,您应考虑find()调用中的逐个错误,而不是将其存储在终止条件中。更好的是:

while start >= 0:
    start = s.find(sub,start+1)
    count += 1

答案 1 :(得分:0)

我可能是错的,但是如果子字符串“重叠”,我认为计数工作不如您期望的那样。例如:

public function postEditPost( Request $request)
{
    $this->validate($request,[
        'body' => 'required'
    ]);

    // checking auth user
    $post = Post::find($request['postId']);
    if(Auth::user != $post->user){
        return redirect()->back();
    }

    // updating the post content
    $post->body = $request['body'];
    $post->update();
    return response()->json(['new_body' => $post->body], 200);
}

这是我的解决方法:

s1="dadad"
s2='dadsdad'

sub="dad"

s1.count(sub) #1
s2.count(sub) #2