在python中搜索字符串的策略?

时间:2014-01-23 05:54:21

标签: python string

在字符串中搜索子字符串的有效方法是什么?      - 我们可以使用python内置的特定功能吗?      - 我们可以将它们转换为列表然后访问列表中的元素吗?      - 我们可以使用for循环来搜索单个元素吗?      - Python程序员有一种普遍接受的方法吗?

了解帮助我解决以下问题的不同策略会很有帮助:

返回字符串"code"出现在给定字符串中任意位置的次数,但我们会接受'd'的任何字母,因此"cope""cooe"计数。

count_code('aaacodebbb') → 1
count_code('codexxcode') → 2
count_code('cozexxcope') → 2

4 个答案:

答案 0 :(得分:2)

您可以使用regex

>>> import re
def count(s):
    return sum(1 for m in re.finditer(r'co.e', s))
... 
>>> count('aaacodebbb')
1
>>> count('codexxcode')
2
>>> count('cozexxcope')
2

此处.匹配任何字符,如果您只想匹配字母,请使用r'co[a-zA-Z]e'

答案 1 :(得分:0)

使用正则表达式可以用于此 -

import re
regex = re.compile(r'co[a-z]e')
li = regex.findall("cozexxcope")           #Output: ['coze', 'cope']

可以找到len(li)。

答案 2 :(得分:0)

+------------+---------+
 |    col1    |  col2   |
 +------------+---------+
 | 0          | a       |
 | 1          | b       |
 +------------+---------+

答案 3 :(得分:0)

这是我的解决方案:

def count_code(str):
  count = 0
  for i in range(0, len(str)-3):
    if str[i] == "c" and str[i+1] == "o" and str[i+3] == "e":
      count = count + 1
  return count