【问题标题】:Returning the amount of times a word appears in a string with a letter missing返回单词在缺少字母的字符串中出现的次数
【发布时间】:2016-01-04 15:31:24
【问题描述】:

假设我有一个字符串"aaatapoaaatacoaaa",我想找到"taco" 出现的次数,但如果字母"c" 被替换为其他字符,我仍然想添加到总数中,所以像这样的词"tapo""taoo" 仍然计数。如果没有像str.find 这样的任何内置字符串搜索方法,我将如何做到这一点?

我只到此为止:

def count_taco(a):
    amount = 0
    for letter in a:

count_taco("aaatapoaaatacoaaa")

【问题讨论】:

  • re.search(r'ta\wo')
  • @BobDylan 我建议len(re.findall('ta.o', s))
  • 没有内置的字符串搜索方法
  • 使用en.wikipedia.org/wiki/… 并修改它,使第三个字母可以是任何东西。
  • 这似乎对我帮助不大:/

标签: python string


【解决方案1】:

这应该可行:

>>> def count_taco(a):

        amount = 0
        chars = 'abcdefghijklmnopqrstuvwxyz'
        for c in chars:
            s = 'ta{}o'.format(c)
            if s in a:
                amount += a.count(s)

        return amount

>>> my_test = 'aaatapoaaatacotaooaaatacotapo'
>>> count_taco(my_test)
5 #tapo - taco - taoo - taco - tapo

【讨论】:

  • 字符串"tacotaco"怎么样?您似乎认为任何“ta.o”只能出现一次。
  • @timgeb .. 感谢您的提醒...:) .. 我在写这个答案时正在考虑另一个问题.. :P
猜你喜欢
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 2018-11-07
  • 1970-01-01
相关资源
最近更新 更多