Character search in Python does not work as intended

Asked 2 years ago, Updated 2 years ago, 13 views

The code you created does not work for the following issues:
What's wrong?

Source: coding_bat string2

problems:

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 "coe" count.

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

created code:

def count_code(str):
  count = 0
  for i in range (len(str)-4):
    if str [i:i+2] == 'co' and str [i+4] == 'e':
      count+=1
  return count

python

2022-09-29 22:38

1 Answers

Invalid index offset value.Also, Python uses the name str as the class name, so it is better to use it as another name.

def count_code(text):
  count = 0
  for i in range (len(text)-3):
    if text [i:i+2] == 'co' and text [i+3] == 'e':
      count+=1
  return count

if__name__=='__main__':
  print(count_code('aaacodebbb'))
  print(count_code('codexcode'))
  print(count_code('cozexxcope'))


2022-09-29 22:38

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.