Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a character is after another

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 !

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading