返回字符串
"code"
出现在任意位置的次数 给定的字符串,除了我们接受'd'
的任何字母,所以"cope"
和"cooe"
计算。
我使用正则表达式使用以下代码实现了这一点:
import re
def count_code(str):
exp = '^co[a-z|A-Z]e$'
count = 0
for i in range(len(str) - 1):
if re.match(exp, str[i:i + 4]):
count = count + 1
return count
print count_code('aaacodebbb') # prints 1
print count_code('codexxcode') # prints 2
print count_code('cozexxcope') # prints 2
有没有其他方法可以在不使用正则表达式的情况下实现此目的?
答案 0 :(得分:1)
你可以试试这个:
def count_code(str):
x=["co"+i+"e" for i in str.lower()]
count = 0
index = 0
for i in x:
if i in str[index:]:
index = str.find(i)+1
count+=1
return count
print count_code('aaacodebbb') # prints 1
print count_code('codexxcode') # prints 2
print count_code('cozexxcope') # prints 2
答案 1 :(得分:1)
对于这个问题,这是一个简单而干净的解决方案:
def count_code(str):
count = 0
for i in range(len(str)):
if str[i:i+2] == "co" and str[i+3:i+4] == "e":
count+=1
return count
答案 2 :(得分:0)
一种方法是你可以使用co * e创建所有可能的字符串,其中*是任何字母
喜欢
x=["co"+i+"e" for i in string.lowercase]
然后迭代
for i in x:
if i in <your string>:
count+=<your string>.count(i)
答案 3 :(得分:0)
您也可以尝试: 使用Python字符串方法'count'
def count_code1(str):
counts=0
for i in range(97,123): #all the lowercase ASCII characters
count+= str.count('co'+chr(i)+'e')
return counts
答案 4 :(得分:0)
def count_code(str):
code = 0
for c in range(len(str)-1):
if str[c+1] == 'o' and str[c:c+4:3] == 'ce':
code+=1
return code
答案 5 :(得分:0)
def count_code(s):
count=0
for i in range(len(s)):
if s[-(i+3):-(i+1)]=='co' and s[-i]=='e':
count=count+1
return count
答案 6 :(得分:0)
您可以像这样重复使用的方式定义逻辑-在这种情况下,无需计数或正则表达式
def count_code(str):
start = 'co' #first 2 letter
start1 = 'e' #last letter
counter = 0 #initiate counter
strlen=len(str) #for each word
for i,x in enumerate(str):
if str[i:i+2]==start:
#for each letter - is that letter and the next equal to start
if len(str[i:strlen]) >=4: #is string long enough?
if str[i+3]==start1: # if so is last letter right?
counter+=1
else:
counter
return counter
答案 7 :(得分:0)
这也应该起作用:
def count_code(str):
counter = 0
for i in range(len(str)-3):
if str[i:i+2] == 'co' and str[i+3] == 'e':
counter +=1
return counter
希望可以帮助您!
答案 8 :(得分:0)
def count_code(str):
a=''
count=0
for char in ("abcdefghijklmnopqrstuvwxyz"):
a=char
count+=str.count("co"+a+"e")
return (count)
答案 9 :(得分:0)
a = 0
for i in range(len(str)-3):
if str[i:i+2] == 'co' and str[i+3] == 'e':
a +=1
return a
答案 10 :(得分:-1)
def count_code(str):
a = 0
for i in range(len(str) - 3):
if str[i:i+2] + str[i+3] == 'coe':
a += 1
return a