学习资源:廖雪峰Python教程——切片
牢记:代码越少越好,逻辑越简单越好
尝试了3种实现方法,其中trim1是类C的实现,逻辑复杂,trim2和trim都是pythonic的,但是trim巧妙地解决了空字符串地情况,代码更加少、更加简洁。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def trim1(s):
idx=-1
for ss in s: #去除首部空格
if(ss==' '):
idx += 1 #最后一个空格所在的下标
else:
s=s[idx+1:]
break
ridx=0
count=0
for ss in s:
if(ss==' '):
count += 1
continue
else:
ridx += 1+count #最后一个非空格字符的下一个下标
count=0
s=s[:ridx]
return s
def trim2(s):
while((s != '') and (s[0]==' ')):
s=s[1:]
while(s != '' and s[-1]==' '):
s=s[:-1]
return s
def trim(s):
while(s[:1]==' '): #即使空字符串也不会索引越界
s=s[1:]
while(s[-1:]==' '): #即使空字符串也不会索引越界
s=s[:-1]
return s
#test
print("trim('hello ') =", trim('hello ') )
print("trim(' hello') =", trim(' hello') )
print("trim(' hello ') =", trim(' hello ') )
print("trim(' hello world ') =", trim(' hello world '))
print("trim('') =", trim('') )
print("trim(' ') =", trim(' ') )
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('测试成功!')
测试结果:
C:\python>trim.py
trim('hello ') = hello
trim(' hello') = hello
trim(' hello ') = hello
trim(' hello world ') = hello world
trim('') =
trim(' ') =
测试成功!
PS: 递归算法都可以写成循环,但是递归很深时会发生“栈溢出”。