python - 计算字符串中的连续数字

标签 python string

想要对字符串中的连续数字进行计数

例如,如果我有:

s = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7abb2a4a6b4a3b5a2f5f3f187a0aaa6aeabe9a4a8aa" rel="noreferrer noopener nofollow">[email protected]</a>'
d = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b565a49525a09085a554f54555e4f5a090b0a0f7b5c565a525715585456" rel="noreferrer noopener nofollow">[email protected]</a>' 

字符串 s 的预期输出为 3。 字符串 d 的预期输出为 4,因为它是字符串内连续数字的最大数量

最佳答案

您可以使用re.findall来获取连续的数字,并以maxlenkey来获取最长的组

s = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9cf0e9fffdeff8eef9aea8aadcfbf1fdf5f0b2fff3f1" rel="noreferrer noopener nofollow">[email protected]</a>'
digits = re.findall(r"\d+", s)
print(len(max(digits, key=len))) # 3

如果您有一个没有数字的字符串,您可以使用 default 参数和长度为 0 的空列表

s = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d51485e5c4e594f587d5a505c5451135e5250" rel="noreferrer noopener nofollow">[email protected]</a>'
digits = re.findall(r"\d+", s)
print(len(max(digits, default=[], key=len))) # 0

关于python - 计算字符串中的连续数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72433900/

相关文章:

java - 使用 Google Guava 格式化字符串

php - 比较 UTF-8 字符串

iphone - 如何在 Objective C 中使用 strlen 查找字符串长度

python - 将文本区域值转换为Python列表

python - 导入错误 : Spatial indexes require either `rtree` or `pygeos` in geopanda but rtree is installed

java - equalsIgnoreCase 方法不适用于 JOptionPane(或 Scanner)输入

python - 使用 pandas 将字符串替换为另一列中的相应字符串

python - 为什么 PyQt connect() 语法如此冗长?

python - 在 python 中为自定义异常设置退出代码

python - 几分钟内的 Matplotlib 烛台