Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to tell if any character appears four times in a row

Here's a piece of Python code that tells me if any character in a string occurs four times in a row:

str = "hello!!!!"
for i in range(0, len(str)-3):
   if str[i] == str[i+1] == str[i+2] == str[i+3]:
       print("yes")

What's a more Pythonic way of writing this, preferably with a regular expression?

I'm aware of this similar question but it asks about a specific character, not any character.

Number of the same characters in a row - python

@JBernardo has an answer with regular expressions but it wants a particular character to match against.

I'm using Python 3, if it matters in your answer.

like image 691
Sol Avatar asked Dec 29 '25 09:12

Sol


1 Answers

Using regex you can use this to find a char that is repeated at least 4 times:

>>> s = 'hello!!!!'

>>> print re.findall(r'(.)\1{3}', s)
['!']

Explanation:

  • (.) - match any character and capture it as group #1
  • \1{3} - \1 is back-reference of captured group #1. \1{3} matches 3 instances of the captured character, this making it 4 repeats.
like image 149
anubhava Avatar answered Dec 30 '25 22:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!