2

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.

Community
  • 1
  • 1
Sol
  • 985
  • 2
  • 10
  • 20
  • 1
    Please read up on regex (specifically, [capture groups](http://stackoverflow.com/documentation/regex/660/capture-groups#t=201607231539015815315)) before asking a question. This is basic stuff. And if you want to actually _understand_ the answers you get, you'll have to read up on regex _anyway_. – Aran-Fey Jul 23 '16 at 15:39
  • 1
    If you want to avoid `re`, try `len(set(my_str[i:i+4]) == 1`. This will give you the number of unique elements from `i` to `i+4`. – MisterMiyagi Jul 23 '16 at 15:40

1 Answers1

3

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.
anubhava
  • 761,203
  • 64
  • 569
  • 643