0

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

3
Contributors
6
Replies
7
Views
5 Years
Discussion Span
Last Post by pyTony
0

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

0

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

Edited by joey_r

0

I thought that was how you write regular expressions?

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

0

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']

Edited by pyTony

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.