[英]Longest consecutive substring of certain character type in python
Is there a pythonic way to find the length of the longest consecutive substring of a certain character type, for instance the length of the longest consecutive substrings of digits/letters/printable characters? 是否有pythonic方法来查找某个字符类型的最长连续子字符串的长度,例如数字/字母/可打印字符的最长连续子字符串的长度?
For example in 例如在
s = "43gfd**54452**jhg4**fddsgf**"
The longest digit substring is of length 5, and the longest letter substring is of length 6. 最长的数字子串的长度为5,最长的字母子串的长度为6。
Regex and max
with length as the key: 正则表达式和
max
长度为关键:
In [12]: s = "43gfd54452jhg4fddsgf"
In [13]: max(re.findall(r'\d+', s), key=len) # digits
Out[13]: '54452'
In [14]: max(re.findall(r'\D+', s), key=len) # non-digits
Out[14]: 'fddsgf'
Similarly, you can change the Regex pattern to get your desired substring type. 同样,您可以更改正则表达式模式以获取所需的子字符串类型。
If there are always "**" between each substring. 如果每个子串之间总是有“**”。 All you have to do is iterate over the different elements, keeping in a variable the longest substring you have found so far.
您所要做的就是遍历不同的元素,在变量中保留到目前为止找到的最长的子字符串。
longest_letter = 0
longest_digit = 0
for el in s.split("**"):
if(el.isalpha()):
len_letter = len(el)
if(len_letter > longest_letter):
longest_letter = len_letter
if(el.isdigit()):
len_digit = len(el)
if(len_digit > longest_digit):
longest_digit = len_digit
print (longest_letter)
print (longest_digit)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.