Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting repeated characters in a string in a row Python

Tags:

python

I would like to check a string for repeated characters in a row until the next space.

For example:
The following string has 4 O's in a row and I would like to detect that somehow.
myString = 'I contain foooour O's in a row without any space'

It doesnt matter what character it is as long as It's being repeated 4 times in a row without any space.

How can I achieve this and what are my options?

like image 296
Persson Avatar asked Apr 13 '26 20:04

Persson


1 Answers

One general solution might be to use re.findall with the pattern ((\S)\2{3,}):

myString = "I contain foooour O's in a row without any space"
matches = re.findall(r'((\S)\2{3,})', myString)
print(matches[0][0])

This prints:

oooo
like image 124
Tim Biegeleisen Avatar answered Apr 15 '26 09:04

Tim Biegeleisen