python

Python程序if语句指定任何非0和非空(null)值为true,0 或者 null为false。

切片

def trim(s):
    # if len(s) == 0:
    #     return s
    # elif s[0] == ' ':
    #     return trim(s[1:])
    # elif s[-1] == ' ':
    #     return trim(s[:-1])
    # else:
    #     return s
    if s[:1] == ' ':
        print(s[:1])
        return trim(s[1:])
    elif s[-1:] == ' ':
        print(s[-1:])
        return trim(s[:-1])
    else:
        return s
if trim('hello  ') != 'hello':
    print(trim('hello  '))
    print('测试失败!')
elif trim('  hello') != 'hello':
    print(trim('hello  '))
    print('测试失败!')
elif trim('  hello  ') != 'hello':
    print(trim('hello  '))
    print('测试失败!')
elif trim('  hello  world  ') != 'hello  world':
    print(trim('hello  '))
    print('测试失败!')
elif trim('') != '':
    print('测试失败!')
elif trim('    ') != '':
    print('测试失败!')
else:
    print('测试成功!')

s = 'hello'
print("--")
print(s[:1])
print("--")
print(s[:-1])
print(s[-3:])

  

原文地址:https://www.cnblogs.com/zhangbao003/p/9115794.html