在 Python 中查找最长的连续字母和数字子字符串
pythonserver side programmingprogramming更新于 2025/10/11 14:04:17
给定的字符串可能是数字和字母的混合。在本文中,我们需要找到字母和数字结合在一起的最大子字符串。
使用 re 模块
正则表达式模块可用于查找所有具有数字或字母的连续子字符串。然后我们应用 max 函数在所有找到的子字符串中仅选择具有最大长度的字母和数字连续子字符串。findall 函数也用于识别并获取所需的子字符串。
示例
import re def longSubstring(str): letter = max(re.findall(r'\D+', str), key=len) digit = max(re.findall(r'\d+', str), key=len) return letter, digit str = 'Hello 459 Congratulations! 234' print(longSubstring(str))
输出
运行上述代码得到以下结果 −
(' Congratulations! ', '459')
使用 len() 和 While 循环
这是一种直接但缓慢的方法,我们设计 while 循环来检查给定字符串中作为子字符串出现的数字和字母的长度。然后我们比较它们的长度并仅选择具有最大长度的子字符串。
示例
def longSubstring(s): max_letterSeq = '' max_digitSeq = '' i = 0 while (i < len(s)): current_letterSeq = '' current_digitSeq = '' # Letters while (i < len(s) and s[i].isalpha()): current_letterSeq += s[i] i += 1 # Digits while (i < len(s) and s[i].isdigit()): current_digitSeq += s[i] i += 1 # Check if not digit or alphabet if (i < len(s) and not (s[i].isdigit()) and not (s[i].isalpha())): i += 1 if (len(current_letterSeq) > len(max_letterSeq)): max_letterSeq = current_letterSeq if (len(current_digitSeq) > len(max_digitSeq)): max_digitSeq = current_digitSeq return max_letterSeq, max_digitSeq str = 'Hello 459 Congratulations! 234' print(longSubstring(str))
输出
运行上述代码得到以下结果 −
('Congratulations', '459')
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

