Home > Mobile >  How to check if a character is after another
How to check if a character is after another

Time:12-10

lets say I have a string y ='rtgxpsa' if the character 'x' is in the string it has to be followed by the character 'p' or 'z' for the function to return True, if it is followed by any other character it returns False.

I cant find any example for something specifically like this but I did try this

def find(word)
for i in word:
      if i == 'x' and i 1 == 'p' or i 1 == 'z':
        return True 
      else:
        return False

print(def('rtgxpsa')) 

Any help would be appreciated ! don't hesitate asking if you need more details !

CodePudding user response:

Your function should look like this

def find(word):
  for i, current_letter in enumerate(word):
    if current_letter == 'x' and (word[i 1] == 'p' or word[i 1]== 'z'):
      return True 
  return False

print(find('rtgxpsa')) 

enumerate(word) returns a generator that has a tuple of the index and the current value

Despite that, your algorithm can be approached differently to be more concise

def find(word):
    return "xp" in word or "xz" in word

CodePudding user response:

There is the in operator which can check for a string in a string. That way you can check for both character combinations at once.

def find(word):
    return "xp" in word or "xz" in word

CodePudding user response:

Use a regex, this gives you a good compromise between flexibility and efficiency:

import re

if re.search(r'x[pz]', word):
    # do something

As a function:

def find(word):
    return bool(re.search(r'x[pz]', word))
  • Related