Discuss / Python / 想问一下大家当我输入一个字符串“ hello ”是可以成功的,但是输入[ ,1,2,3,4, ] 就没办法成功,上面这个是还应该怎么更改吗?

想问一下大家当我输入一个字符串“ hello ”是可以成功的,但是输入[ ,1,2,3,4, ] 就没办法成功,上面这个是还应该怎么更改吗?

Topic source

杨森-ys

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

def trim(S):

    if S[:1]==" ":

       return trim(S[1:])

    elif S[-1:]==" ":

        return trim(S[:-1])

    return S

print(trim("  hhhhello  "))

杨森-ys

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

    if s=="":

        return s

    while s[:1]==" ":

        s=s[1:]

    while s[-1:]==" ":

        s=s[:-1]

    return s

杨森-ys

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

在while循环之前进行判定,如果是空反馈原字符串即可。


  • 1

Reply