该程序的目的是按字母顺序打印变量s中最长的子字符串。

s ='abchae'
currentlen = 0
longestlen = 0
current = ''
longest = ''
alphabet = 'abcdefghijklmnopqrstuvwxyz'

for char in s:

    for number in range(0,len(s)):
    if s[number] == char:
        n = number

    nxtchar = 1
    alphstring = s[n]
    while alphstring in alphabet == True and n+nxtchar <= 5:
        alphstring += s[n+nxtchar]
        nxtchar += 1
        currentlen = len(alphstring)
        current = alphstring

        if currentlen > longestlen:
            longest = current

print longest


运行时,该程序不打印任何内容。我似乎看不出代码有什么问题。任何帮助,将不胜感激。

最佳答案

我会为此使用regex

import re
string = 'abchae'
alphstring = re.compile(r'a*b*c*d*e*f*g*h*i*j*k*l*m*n*o*p*q*r*s*t*u*v*w*x*y*z*', re.I)

longest = ''
for match in alphstring.finditer(string):
    if len(match.group()) > len(longest):
        longest = match.group()

print(longest)


输出:

abch


注意:regex表达式中的标志re.I导致regex忽略大小写。如果这不是您想要的行为,则可以删除该标志,它只会匹配小写字符。

09-11 22:14