求最长尾随子串的长度

2024-09-29 23:15:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要提取最长的子字符串的长度,该子字符串在给定字符串的末尾结束,并且包含完全相同的字符。你知道吗

例如,给定"aaabbbb",所需的子串将是"bbbb"length = 4

虽然我可以用while/for循环想出许多方法来实现这一点,但我想知道是否有更优雅的方法来实现这一点。有没有这方面的模块?我不想使用for循环来查找这个子字符串。有可能吗?你知道吗


Tags: 模块方法字符串for字符length末尾while
2条回答
>> s = "aaabbbb"
>> len(s) - len(s.rstrip(s[-1]))
4

^{}的docstring

S.rstrip([chars]) -> string or unicode

Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping

所以这个解决方案取原始字符串的长度,并从中减去一个字符串的长度,其中所有相同的最后一个字符都被去除。你知道吗

您可以尝试使用^{}模块和^{}

>>> s = "aaabbbb"
>>> import re
>>> pat = re.escape(s[-1]) + '*$'
>>> pat
'b*$'
>>> re.search(pat,s).group()
'bbbb'

其他情况

>>> s = 'bbbabbbbb'
>>> re.search(pat,s).group()
'bbbbb'
>>> s = 'abcd'
>>> re.search(pat,s).group()
'd'

然后可以使用len来查找长度。你知道吗

相关问题 更多 >

    热门问题