Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter strings where there are n equal characters in a row

Is there an option how to filter those strings from list of strings which contains for example 3 equal characters in a row? I created a method which can do that but I'm curious whether is there a more pythonic way or more efficient or more simple way to do that.

list_of_strings = []


def check_3_in_row(string):
    for ch in set(string):
        if ch*3 in string:
            return True
    return False

new_list = [x for x in list_of_strings if check_3_in_row(x)]

EDIT: I've just found out one solution:

new_list = [x for x in set(keywords) if any(ch*3 in x for ch in x)]

But I'm not sure which way is faster - regexp or this.

like image 946
Milano Avatar asked May 25 '15 12:05

Milano


1 Answers

You can use Regular Expression, like this

>>> list_of_strings = ["aaa", "dasdas", "aaafff", "afff", "abbbc"]
>>> [x for x in list_of_strings if re.search(r'(.)\1{2}', x)]
['aaa', 'aaafff', 'afff', 'abbbc']

Here, . matches any character and it is captured in a group ((.)). And we check if the same captured character (we use the backreference \1 refer the first captured group in the string) appears two more times ({2} means two times).

like image 161
thefourtheye Avatar answered Oct 29 '22 16:10

thefourtheye