Hello, long time lurker first time poster. I was looking for some help on a problem I came across on a python site.

I am supposed to count the number of times 'code' apears in my string. But any letter can be in the place of the 'd' in 'code'; 'cofe', 'coqe', ect. I can't figure out how to use a regular expressions, I tried '^co/./$e' but it is not working. Thanks in advance!

I came up with:

def count_code(str):
x = str.count('code')
return x

print count_code('aaacodebbb') # 1
print count_code('codexxcode') # 2
print count_code('cozexxcope') # 2

Recommended Answers

All 6 Replies

Do you mean that you want to count the occurances without regular expressions as you are not even importing re module?

No, I do want to use regular expressions I totally forgot about importing re. It's still not working though?

import re

def count_code(str):
x = str.count('^co/./e')
return x

print count_code('aaacodebbb') # 1
print count_code('codexxcode') # 2
print count_code('cozexxcope') # 2

where you got those / from? And why ^?

I thought that was how you write regular expressions?

^ matchest the beginning of the string, $ matches the end, . matches any letter?

And why should you match begining of string?

import re
expression = r'^co/./e'
print re.findall(expression, 'co/f/e cofe co/f/e')

['co/f/e']

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.