题目:利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法
环境:windows 7+anaconda3 64bit+pycharm
方法一:
def trim(s):
if s[:1]!=' ' and s[1:]!=' ':
return s
elif s[:1]==' ':
return s[1:]
else:
return s[:1]
print(trim(' Hello world!'))
print(trim('Hello world! '))
方法二:
def trim(s):
for i in range(len(s)):
if s[0] == ' ':
s = s[1:]
for k in range(len(s)):
if s[-1] == ' ':
s = s[:-1]
return s
print(trim(' Hello world!'))
print(trim('Hello world! '))
切片在python中用处很大,可以实现很多循环才能完成的操作。