Python字符串索引和字符比较

Python字符串索引和字符比较,python,string,search,slice,Python,String,Search,Slice,所以我试着做这样的事情 #include <stdio.h> int main(void) { char string[] = "bobgetbob"; int i = 0, count = 0; for(i; i < 10; ++i) { if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b')

所以我试着做这样的事情

#include <stdio.h>

int main(void)
{
    char string[] = "bobgetbob";
    int i = 0, count = 0;
    for(i; i < 10; ++i)
    {
            if(string[i] == 'b' && string[i+1] == 'o' && string[i+2] == 'b')
                    count++;
    }
    printf("Number of 'bobs' is: %d\n",count);

}
count = 0
s = "bobgetbob"
for i in range(0,len(s)):
    if s[i] == 'b' and s[i+1] == 'o' and s[i+2] == 'b':
        count += 1
print "Number of 'bobs' is: %d" % count
每当我得到一个恰好以“b”结尾的字符串,或者倒数第二个是“b”,后跟一个“o”,我就会得到一个索引超出范围的错误。现在在c中这不是一个问题,因为它仍然会执行与垃圾值的比较,我假设垃圾值与c一起工作

如何在python中执行此操作而不超出范围

我可以这样迭代字符串本身吗

for letter in s:
    #compare stuff
for letter in s:
#compare stuff 
如何使用上述方法比较字符串中的特定索引?如果我尝试使用

letter == 'b' and letter + 1 == 'o'
这在python中是无效的语法,我的问题是我在用c语言思考,我不能完全确定解决这种情况的正确语法。 我知道像这样切丝

for i in range(0,len(s)):
    if s[i:i+3] == "bob":
        count += 1
这解决了这个特定的问题,但我觉得使用特定的索引位置来比较字符是一个非常强大的工具。如果没有像上面的第一个python示例那样出现一些破坏它的情况,我就无法用python正确地完成这项工作

我可以这样迭代字符串本身吗

for letter in s:
    #compare stuff
for letter in s:
#compare stuff 
如何使用上述方法比较字符串中的特定索引

在不特别提及索引的情况下进行此类比较的python方法是:

for curr, nextt, nexttt in zip(s, s[1:], s[2:]):
    if curr == 'b' and nextt == 'o' and nexttt == 'b':
         count += 1
这样可以避免索引外错误。您还可以使用理解,这样就不需要初始化和更新
count
变量。这行代码与您的C代码相同:

>>> sum(1 for curr, nextt, nexttt in zip(s, s[1:], s[2:])
          if curr == 'b' and nextt == 'o' and nexttt == 'b')
2
工作原理: 这是列表之间压缩的结果:

>>> s
'bobgetbob'
>>> s[1:]
'obgetbob'
>>> s[2:]
'bgetbob'

>>> zip(s, s[1:], s[2:])
[('b', 'o', 'b'),
 ('o', 'b', 'g'),
 ('b', 'g', 'e'),
 ('g', 'e', 't'),
 ('e', 't', 'b'),
 ('t', 'b', 'o'),
 ('b', 'o', 'b')]
在循环中,您迭代列表,将每个元组解压为三个变量

最后,如果您确实需要索引,可以使用:

试试这个-即转到len(s)-2,因为在这一点之后,你将永远不会得到一个bob开始

count = 0
s = "bobgetbob"
for i in range(len(s) - 2):
    if s[i] == 'b' and s[i + 1] == 'o' and s[i + 2] == 'b':
        count += 1
print "Number of 'bobs' is: %d" % count

生成器表达式和求和是解决此问题的更好方法:

print("number of bobs {}".format(sum(s[i:i+3] == "bob" for i in xrange(len(s)) )))
你也可以通过索引来作弊,例如
s[i+2:i+3]
不会抛出索引器:

count = 0
s = "bobgetbob"
for i in range(0,len(s)):
    print(s[i+1:i+1])
    if s[i] == 'b' and s[i+1:i+2] == 'o' and s[i+2:i+3] == 'b':
        count += 1
print "Number of 'bobs' is: %d" % count
Number of 'bobs' is: 2

一般来说,这是一种缓慢的方法;您最好尽可能多地委托给更高性能的对象方法,如
str.find

def how_many(needle, haystack):
    """
    Given
        needle:   str to search for
        haystack: str to search in

    Return the number of (possibly overlapping)
      occurrences of needle which appear in haystack

    ex,  how_many("bb", "bbbbb")  => 4
    """
    count = 0
    i = 0      # starting search index
    while True:
        ni = haystack.find(needle, i)
        if ni != -1:
            count += 1
            i = ni + 1
        else:
            return count

how_many("bob", "bobgetbob")    # => 2

haystack.find(pineel,i)
返回在索引
i
上或之后开始的
pineel
的下一次出现的开始索引,或者如果没有出现这种情况,则返回
-1

所以


我刚刚意识到,如果我知道我要搜索的单词的长度,我可以限制我要搜索的字符串的范围,这样我就不会越界。例如,因为bob有三个字母长,所以在For循环中检查第二个到最后一个字母没有意义,因为bob必须至少有三个字母长,我将范围限制为两个,并且我检查的最后一个字母是第三个到最后一个字母。
count = 0
for i in range(0,len(s)-2):
    if s[i] == 'b' and s[i+1] == 'o' and s[i+2] == 'b':
        count += 1
print "Number of 'bobs' is: %d" % count