统计字符串出现的个数
1、题目说明:在函数中输入一串带有字母数字的字符串,并指定某个字母,统计它在该字符串中出现的个数
①Python的简单实现:
def count(word, s):
word = word.upper()
s = s.upper()
res = 0
for i in word:
if i == s:
res += 1
return res
注释:s转换为大写必须在for循环前实现,如果写到if条件中,则返回的结果始终为0
②字典的实现
def count(word, s):
frequency = {}
word = word.upper()
s = s.upper()
for w in word:
if w not in frequency:
frequency[w] = 1
else:
frequency[w] += 1
return frequency[s]
print(count(word = "Imahandsomeboy", s='o'))
③通过字符串的count方法实现:
def count(word,s):
word = word.upper()
s = s.upper()
res = word.count(s)
return res
print(count("hellowordsss", 's'))