2024-09-29 23:15:37 发布
网友
我需要提取最长的子字符串的长度,该子字符串在给定字符串的末尾结束,并且包含完全相同的字符。你知道吗
例如,给定"aaabbbb",所需的子串将是"bbbb"和length = 4
"aaabbbb"
"bbbb"
length = 4
虽然我可以用while/for循环想出许多方法来实现这一点,但我想知道是否有更优雅的方法来实现这一点。有没有这方面的模块?我不想使用for循环来查找这个子字符串。有可能吗?你知道吗
while
for
>> s = "aaabbbb" >> len(s) - len(s.rstrip(s[-1])) 4
从^{}的docstring
S.rstrip([chars]) -> string or unicodeReturn 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.rstrip([chars]) -> string or unicode
S.rstrip([chars])
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来查找长度。你知道吗
len
从^{} 的docstring
所以这个解决方案取原始字符串的长度,并从中减去一个字符串的长度,其中所有相同的最后一个字符都被去除。你知道吗
您可以尝试使用^{} 模块和^{}
其他情况
然后可以使用
len
来查找长度。你知道吗相关问题 更多 >
编程相关推荐