[英]Python: How to search for repetitive strings within a string
If I had a string:如果我有一个字符串:
x = 'ab123abc123123123123abcabcabc123123123123123123123abcabc'
What would be the best approach to print the length of the longest sequence of '123' found in a row?打印连续找到的最长“123”序列的长度的最佳方法是什么? For this string, I would want to get 7.对于这个字符串,我想得到 7。
I have tried using regex, but I couldn't even find a way to return the substring with two or more occurrences.我试过使用正则表达式,但我什至找不到一种方法来返回出现两次或多次的 substring。 I have not used regex a lot and the best I came up with is:我没有经常使用正则表达式,我想到的最好的是:
re.findall('123+', x)
I also tried creating a way from scratch with loops, but that also failed.我也试过用循环从头开始创建一种方法,但也失败了。
I am stuck at this point and would really appreciate any help我被困在这一点上,非常感谢任何帮助
Here's one way to go about it:这是 go 的一种方式:
x = 'ab123abc123123123123abcabcabc123123123123123123123abcabc'
index = 0
count = 0
longest = 0
while index < len (x) :
if x [index] == '1' :
index += 1
if x [index] == '2' :
index += 1
if x [index] == '3' :
count += 1
if count > longest :
longest = count
else : count = 0
index += 1
print (longest)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.