Discuss / Python / 完全符合要求的作业

完全符合要求的作业

Topic source

def trip(s):

    #使用递归,清除字符串头部空白区域

    if len(s) == 0:

        return s

    if s[0]==' ' or s[0]=='\t':  # 考虑到空白有“space”和“tab”两种情况

        s=trip(s[1:])           #   先清除头部空白

    if s[-1]==' ' or s[-1]=='\t':

        s=trip(s[:-2])        #      再去除尾部空白

    return s

Ethereal

#2 Created at ... [Delete] [Delete and Lock User]

运行到最后一个测试报错,报错信息如下:

Traceback (most recent call last):

  File "e:\PY代码\练习\去字符串首尾空格.py", line 20, in <module>

    elif trim('    ') != '':

  File "e:\PY代码\练习\去字符串首尾空格.py", line 5, in trim

    s=trim(s[1:])

  File "e:\PY代码\练习\去字符串首尾空格.py", line 5, in trim

    s=trim(s[1:])

  File "e:\PY代码\练习\去字符串首尾空格.py", line 5, in trim

    s=trim(s[1:])

  File "e:\PY代码\练习\去字符串首尾空格.py", line 6, in trim

    if s[-1]==' ' or s[-1]=='\t':

IndexError: string index out of range

Ethereal

#3 Created at ... [Delete] [Delete and Lock User]

源代码:

def trim(s):

    if len(s)==0:

        return s

    if s[0]==' ' or s[0]=='\t':

        s=trim(s[1:])

    if s[-1]==' ' or s[-1]=='\t':

        s=trim(s[:-2])

    return s

rainux

#4 Created at ... [Delete] [Delete and Lock User]
s=trim(s[:-2]) // 这里错了
应改为
s=trim(s[:-1])

Moria_XD

#5 Created at ... [Delete] [Delete and Lock User]

def trim(s):

    while s[:1] == ' ':

        s = s[1:]

    while s[-1:-2:-1] == ' ':

        s = s[:-1]

    return s


  • 1

Reply