Discuss / Python / 练习题

练习题

Topic source

唯情恋昉

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

利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:

# -*- coding: utf-8 -*-
def trim(s):
    # 当字符串为''时,返回''
    if len(s) == 0:
        return s
    
    # 记录空格个数
    count = 0
    # 索引
    i = 0
    # 去除字符串首空格
    while i < len(s):
        if s[i] == ' ':
            count += 1
        # 当索引到最后一个元素时,空格数和索引数加一一样,说明这个字符串都是空格,返回''
        if i == len(s) - 1 and count == i + 1:
            return ''
        # 当前索引元素为' ',下一索引元素不为空,且空格数和索引数加一一样,说明从零索引到当前索引都是空格,截取尾部分
        if i != len(s) - 1 and s[i] == ' ' and s[i+1] != ' ' and count == i + 1:
            s = s[i+1:len(s)]
            break
        i += 1
    
    count = 0
    j = len(s) - 1
    # 去除字符串尾空格
    while j >= 0:
        if s[j] == ' ':
            count += 1
        # 当前索引元素为' ',上一索引元素不为空,且空格数和长度减去索引的值一致,说明从当前索引到最后索引都是空格,截取首部分
        if j != 0 and s[j] == ' ' and s[j-1] != ' ' and count == len(s) - j:
            s = s[:j]
            break
        j -= 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('测试成功!')

唯情恋昉

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

看了下评论区,好家伙~ 几行就搞定了,真心学到不少


  • 1

Reply