KishB87
KishB87

Reputation: 303

Strategies for searching through strings in python?

What are efficient ways to search for substrings in strings? - Are there specific functions built in python we can use? - Can we convert them to lists then access elements in the list? - Can we use for loops to search through individual elements? - Is there one generally accepted method by Python programmers?

It would be helpful to understand the different strategies to help me solve the following problem:

Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.

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

Upvotes: 0

Views: 564

Answers (4)

Rafael Sartori
Rafael Sartori

Reputation: 11

This was my solution:

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

Upvotes: 0

Zycarsus
Zycarsus

Reputation: 1

    def count_code(str):
      count = 0 #set count to 0 initially
        #For loops number of times that there are chars
      for i in range(len(str)-1): 
         #looks for "co", [any char] and "e"
        if str[i:i+2] == "co" and str[i+3:i+4] == "e":  
            #add up the number of times this happens and return it
          count+= 1 
    return count

Upvotes: 0

Kamehameha
Kamehameha

Reputation: 5488

Using regular expression would work for this-

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

Count can be found be the len(li).

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251146

You can use 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

Here . matches any character, if you only want to match alphabets then use r'co[a-zA-Z]e'.

Upvotes: 2

Related Questions