Python 不使用count()对字符串中的字母进行计数
我尝试在不使用count()的情况下执行count函数,它正在工作,一切正常,但当我尝试在一个单词中搜索两个字母时,返回0。当我尝试在一个字母中搜索一个单词时,它的工作是正常的Python 不使用count()对字符串中的字母进行计数,python,Python,我尝试在不使用count()的情况下执行count函数,它正在工作,一切正常,但当我尝试在一个单词中搜索两个字母时,返回0。当我尝试在一个字母中搜索一个单词时,它的工作是正常的 def count(str, sub): found = 0 for key in str: if key == sub: found += 1 return found str = input("Enter a string: ")
def count(str, sub):
found = 0
for key in str:
if key == sub:
found += 1
return found
str = input("Enter a string: ") #or we can initialize a string
sub = input("Enter a substring: ") #or we can initialize a substring
count(str, sub)
print ("letter: ", sub)
print ("count: ", count(str, sub))
以下内容适用于所有长度的子字符串
def count(str, sub):
found = 0
for i in range(1,len(str)+1): #iterate for all length substrings
for j in range(len(str)-i+1): #iterate for different starting positions of substrings.
key = str[j:j+i]
if key == sub:
found += 1
return found
以下内容适用于所有长度的子字符串
def count(str, sub):
found = 0
for i in range(1,len(str)+1): #iterate for all length substrings
for j in range(len(str)-i+1): #iterate for different starting positions of substrings.
key = str[j:j+i]
if key == sub:
found += 1
return found
按照你的方法,我建议你这样做:
def count(string, sub):
found = 0
size = len(sub)
for i in range(len(string) + 1 - size):
if string[i:i+size] == sub:
found += 1
return found
这样,您可以将其用于任何大小的
sub
按照您的方法,我建议您执行以下操作:
def count(string, sub):
found = 0
size = len(sub)
for i in range(len(string) + 1 - size):
if string[i:i+size] == sub:
found += 1
return found
def count(string, sub):
found = 0
for c in range(len(string)):
start = c
end = -(len(string)-len(sub)-c) if -(len(string)-len(sub)-c) != 0 else None
if string[start:end] == sub:
found += 1
return found
string = input("Enter a string: ") #or we can initialize a string
sub = input("Enter a substring: ") #or we can initialize a substring
print ("letter: ", sub)
print ("count: ", count(string, sub))
这样,您就可以将其用于任意大小的
sub
for key in str:
将始终一次搜索一个字母,因此您不能使用现有逻辑一次搜索两个字符。您的循环正在一次搜索一个字母time@tbjorch我的意思是不做print('bctestbc'.count('bc'))
返回2
@lllrnr101是现在我意识到for-for循环将只包含一个字母,有没有想法将其转换为单词而不是一个字母一个字母?@VanshSachdeva是的现在我意识到,我正在尝试寻找另一种方法,而不是一个字母一个字母地输入str:将始终一次只包含一个字母,因此,您不能使用现有逻辑一次搜索两个字符。您的循环一次搜索一个字母time@tbjorch我的意思是,如果不执行print('bctestbc'.count('bc'))
返回2
@lllrnr101 yes,现在我意识到for循环将返回一个字母,有没有想过要变成一个单词而不是一个字母一个字母的?@VanshSachdeva是的,现在我意识到,我正在尝试寻找另一种没有字母一个字母的方法,正如你在这里看到的,这种方法不适用于这封信,正如你在这里看到的,这种方法不适用于这封信
def count(string, sub):
found = 0
for c in range(len(string)):
start = c
end = -(len(string)-len(sub)-c) if -(len(string)-len(sub)-c) != 0 else None
if string[start:end] == sub:
found += 1
return found
string = input("Enter a string: ") #or we can initialize a string
sub = input("Enter a substring: ") #or we can initialize a substring
print ("letter: ", sub)
print ("count: ", count(string, sub))