统计字符串中字母数字出现的个数

统计字符串出现的个数

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'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值