查找另一个字符串中sub_string的出现次数

时间:2019-04-01 16:51:38

标签: python-3.x

string = 'WoW!ItSCoOWoWW'
sub_string = 'oW'
count = 0

st = list(string)


for x in range(len(st)):
    if ord(string[x]) == ord(sub_string[0]):
        s1 = ''.join(string[x:])
        if sub_string in s1:

            count +=1
print(count)

问题:      ord()函数无法区分“ o”和“ O”(在字符串中)。

2 个答案:

答案 0 :(得分:0)

有一个内置函数:str.count()

https://www.tutorialspoint.com/python/string_count.htm

您的代码存在问题,位于错误行之前的print语句中。您缺少括号。

答案 1 :(得分:0)

您放错了括号print(ord(string[x]), ord(sub_string)
更新此行以修复您的代码:

print(ord(string[x]), ord(sub_string))
相关问题