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.
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).
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