Here's a piece of Python code that tells me if any character in a string occurs four times in a row:
下面是一段Python代码,它告诉我字符串中的任何字符是否连续出现4次:
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?
什么是更python的写法,最好是正则表达式?
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
行python中相同字符的数目
@JBernardo has an answer with regular expressions but it wants a particular character to match against.
@JBernardo有一个正则表达式的答案,但它想要一个特定的字符与之匹配。
I'm using Python 3, if it matters in your answer.
我用的是python3,如果它对你的答案有影响的话。
1 个解决方案
#1
3
Using regex you can use this to find a char that is repeated at least 4 times:
使用regex,您可以使用它查找至少重复4次的char:
>>> s = 'hello!!!!'
>>> print re.findall(r'(.)\1{3}', s)
['!']
Explanation:
解释:
-
(.)
- match any character and capture it as group #1 - 匹配任何字符并将其捕获为组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. - \1{3} - \1是捕获的组#1的反向引用。\1{3}匹配捕获字符的3个实例,这使它重复4次。
#1
3
Using regex you can use this to find a char that is repeated at least 4 times:
使用regex,您可以使用它查找至少重复4次的char:
>>> s = 'hello!!!!'
>>> print re.findall(r'(.)\1{3}', s)
['!']
Explanation:
解释:
-
(.)
- match any character and capture it as group #1 - 匹配任何字符并将其捕获为组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. - \1{3} - \1是捕获的组#1的反向引用。\1{3}匹配捕获字符的3个实例,这使它重复4次。