gpt4 book ai didi

Python字符串索引和字符比较

转载 作者:行者123 更新时间:2023-12-01 22:33:48 25 4
gpt4 key购买 nike

所以我正在尝试做这样的事情

#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);

}

但在 python 术语中是这样工作的

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

如何使用上述方法比较字符串中的特定索引?如果我尝试使用

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 示例那样破坏它。

最佳答案

Could i iterate through the string itself like so?

for letter in s:
#compare stuff

How would I compare specific indexes in the string using the above method?

在不具体引用索引的情况下进行此类比较的 pythonic 方式是:

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')]

在循环中,您迭代列表,将每个元组解包为三个变量。

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

>>> for i, c in enumerate(s):
print i, c
0 b
1 o
2 b
3 g
4 e
5 t
6 b
7 o
8 b

关于Python字符串索引和字符比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28034947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com