I'm working on processing words in python and I want to see if a string has 3 or more occurances of the same letter back to back .Is there a better way to do that other than a nested for loop ? example: "helllooooo"
As another option, looping once but checking the next two letters ahead will work, and the loop is smaller since you don't have to check the last two characters AND you can break as soon as you find a hit:
for i in range(0, len(instring)-2):
if (instring[i] == instring[i+1] == instring[i+2]):
print(f"{instring[i]} occurs three or more times.")
break
Optionally, if you need to know the value or position in the string where these sequences appear, you could generate a list that holds the index of the letter that start a three-in-a-row sequence:
print([[i,c] for i,c in enumerate(instring) if i < len(instring)-2 and (c == instring[i+1] == instring[i+2])])
This will generate a list of lists with the letter and the position in the word where sequence of 3 is found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With