Discuss / Python / 2022/7/24

2022/7/24

Topic source

感觉自己写麻烦了 and前后顺序很重要 不然就会越界

def trim(s):    while (s!='')and(s[0] == ' ' or s[-1] == ' '):        if s[0] == ' ':            s = s[1:]        if s[-1] == ' ':            s = s[:-1]    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('测试成功!')

def trim(s):

    while (s!='')and(s[0] == ' ' or s[-1] == ' '):

        if s[0] == ' ':

            s = s[1:]

        if s[-1] == ' ':

            s = s[:-1]

    return s


  • 1

Reply