# 练习题,去除字符串首尾的空格,不要调用str的strip()
def trim(s):
while s[0] == ' ':
s = s[1:]
continue
while s[-1] == ' ':
s = s[:-1]
continue
return s
s1 = ' hello'
s2 = 'hello '
s3 = ' hello '
s4 = ' hello world '
s5 = ' hello world '
print(list(s1))
print(list(trim(s1)))
print('------------------------------')
print(list(s2))
print(list(trim(s2)))
print('------------------------------')
print(list(s3))
print(list(trim(s3)))
print('------------------------------')
print(list(s4))
print(list(trim(s4)))
print('------------------------------')
print(list(s5))
print(list(trim(s5)))
输出
[' ', 'h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
------------------------------
['h', 'e', 'l', 'l', 'o', ' ']
['h', 'e', 'l', 'l', 'o']
------------------------------
[' ', 'h', 'e', 'l', 'l', 'o', ' ']
['h', 'e', 'l', 'l', 'o']
------------------------------
[' ', 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ']
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
------------------------------
[' ', ' ', ' ', 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', ' ', ' ']
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>>