简单的删除前后的空格

def trim(s):
start = 0
for i in range(0,len(s)):
if s[i] != ' ':
start = i
break
else:
start = len(s) -1

end = -1    
for i in range(1,len(s)):
    if s[-1*i] != ' ':
        end = i*-1
        break
else:
    end = -1

if start == len(s) -1:
    return ''

if end == -1:
    return s[start:]

return s[start:end+1]

if trim('hello ') != 'hello':
print('测试失败!1')
elif trim(' hello') != 'hello':
print('测试失败!2')
elif trim(' hello ') != 'hello':
print('测试失败!3')
elif trim(' hello world ') != 'hello world':
print('测试失败!4')
elif trim('') != '':
print('测试失败!5')
elif trim(' ') != '':
print('测试失败!6')
else:
print('测试成功!')

你可能感兴趣的:(简单的删除前后的空格)