计算字符串中的连续数字
counting consecutive digits in a string
想要对字符串中的连续数字进行计数
例如,如果我有:
s = 'lucasdre246@gmail.com'
d = 'maria23antoneta2014@gmail.com'
字符串 s
的预期输出为 3。
字符串 d
的预期输出是 4,因为它是字符串
中连续数字的最大连续数
下面的函数就是你要找的:
def max_consecutive_digits(string):
"""
Returns the maximum number of consecutive digits in a string.
"""
max_consecutive = 0
current_consecutive = 0
for char in string:
if char.isdigit():
current_consecutive += 1
else:
if current_consecutive > max_consecutive:
max_consecutive = current_consecutive
current_consecutive = 0
if current_consecutive > max_consecutive:
max_consecutive = current_consecutive
return max_consecutive
可以用re.findall
得到连续的数字,得到最长的一组max
,len
为key
s = 'lucasdre246@gmail.com'
digits = re.findall(r"\d+", s)
print(len(max(digits, key=len))) # 3
如果你有一个没有数字的字符串,你可以使用 default
参数和一个长度为 0
的空列表
s = 'lucasdre@gmail.com'
digits = re.findall(r"\d+", s)
print(len(max(digits, default=[], key=len))) # 0
想要对字符串中的连续数字进行计数
例如,如果我有:
s = 'lucasdre246@gmail.com'
d = 'maria23antoneta2014@gmail.com'
字符串 s
的预期输出为 3。
字符串 d
的预期输出是 4,因为它是字符串
下面的函数就是你要找的:
def max_consecutive_digits(string):
"""
Returns the maximum number of consecutive digits in a string.
"""
max_consecutive = 0
current_consecutive = 0
for char in string:
if char.isdigit():
current_consecutive += 1
else:
if current_consecutive > max_consecutive:
max_consecutive = current_consecutive
current_consecutive = 0
if current_consecutive > max_consecutive:
max_consecutive = current_consecutive
return max_consecutive
可以用re.findall
得到连续的数字,得到最长的一组max
,len
为key
s = 'lucasdre246@gmail.com'
digits = re.findall(r"\d+", s)
print(len(max(digits, key=len))) # 3
如果你有一个没有数字的字符串,你可以使用 default
参数和一个长度为 0
s = 'lucasdre@gmail.com'
digits = re.findall(r"\d+", s)
print(len(max(digits, default=[], key=len))) # 0