def my_trim(s):
while True:
if(str.startswith(s,' ')):#字符串以空格开头
s = s[1:]
elif(str.endswith(s,' ')):#字符串以空格结尾
s = s[:-1]
else:
break
return s
if(my_trim(' hel lo ') == 'hel lo'):
print('you are great!')
else:
print('please change you mind ')
方法二:
思路:循环判断第一个字符,以及最后一个字符是否是空格
def my_trim_demo(s):
while(True):
if(s[:1]!=' ' and s[-1:] != ' '):
return s
elif s[:1] == ' ' :
s = s[1:]
elif s[-1:] == ' ':
s = s[:-1]
print(my_trim_demo(' hello world ') == 'hello world')