Code Challenge: String Methods Exercise 4 Count Multi X

Could my solution be more optimal for finding a sub string in a string?

def count_multi_char_x(word,x):
  lst = []
  index = 0
  count = 0
  while index < len(word):
    lst.append(word[index:len(x)+index])
    if x == lst[index]:
      count+=1
    index += 1
  return count

Hello @tag9677509016, welcome to the forums! Why do you create a new list

and use it here:

You can also access strings with indexing:

stringVar = "somestring"
print(stringVar[2])#prints "m" 

Other than that, you could use a for loop to iterate through word (meaning you wouldn’t have to use the index variable), but that is very minor.

Thanks. The reason why I created a new list was because i thought that i needed to store it somewhere but I’ve realized I could have just tested x with the word using the index.

1 Like