Discuss / Python / 练习

练习

Topic source

Neri.

#1 Created at ... [Delete] [Delete and Lock User]
def trim(s):
    while True:
        if len(s)==0:
            return s
        elif s[0]==' ':
            s=s[1:]
        elif s[-1]==' ':
            s=s[0:-1]
        else:
            return s
    return s

# 测试:
if trim('hello  ') != 'hello':
    print('测试失败!')
elif trim('  hello') != 'hello':
    print('测试失败!')
elif trim('  hello  ') != 'hello':
    print('测试失败!')
elif trim('  hello  world  ') != 'hello  world':
    print('测试失败!')
elif trim('') != '':
    print('测试失败!')
elif trim('    ') != '':
    print('测试失败!')
else:
    print('测试成功!')

只比较了首个和最后一个元素,如果第2个,或倒数第2个是“ ”或“tab”键呢

南街

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

while True 可以无限循环直到没有空格了

@魅影迷惑你,那就if x =="" or "(在编辑器里按tab)"    elif x[0]==" " or " ":


  • 1

Reply