Discuss / Python / 去掉首尾的空格

去掉首尾的空格

Topic source

向阳

#1 Created at ... [Delete] [Delete and Lock User]
def trim(s):
    if not isinstance(s,(str)): 
        raise TypeError('参数类型错误:请输入字符串')
    if s == '': #如果字符串为空,直接返回s值
        return s
    while s[0] == ' ': #前面可能有多个空格,因此使用while循环进行条件判断
        s = s[1:]
        if s == '':  #如果字符串都是空格,则最后的结果为空,直接返回空值。
            return s
    while 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('测试成功!')
    
测试成功!

循环前的if语句可以不要,如果为空值还是空格,都不会显示


  • 1

Reply