import re
def countDog1(st):
count = 0
for word in st.lower().split():
if word == 'dog':
count += 1
return count
print('Function countDog1: ' + str(countDog1('hello dog I am a dog!')))
def countDog2(st):
count = 0
st = re.sub(r'([^\s\w]|_)+', '', st)
for word in st.lower().split():
if word == 'dog':
count += 1
return count
print('Function countDog2: ' + str(countDog2('hello dog I am a dog!')))
我假设意外行为是由字符串中的非字母数字字符引起的:
退货
因此“狗”只会被计算一次。下面是一个如何用
re
解决这个问题的例子:输出:
你在问题中写的函数似乎起作用了。一定要把回程板缩进好。您可能在代码中将其缩进了一个级别。你知道吗
相关问题 更多 >
编程相关推荐