# 1.切片：利用切片操作，实现一个trim()函数，去除字符串首尾的空格，注意不要调用str的strip()方法：

``````def trim(s):
print(s)
if s[:1]!=' 'and s[-1:]!=' ':
return s
elif s[:1]==' ':
return trim(s[1:]) #利用递归函数
print(s[1:])
else:
return trim(s[:-1])
print(s[:-1])
# 测试:

if trim('hello  ') != 'hello':
print('test failed!')
elif trim('  hello') != 'hello':
print('test failed!')
elif trim('  hello  ') != 'hello':
print('test failed!')
elif trim('  hello  world  ') != 'hello  world':
print('test failed!')
elif trim('') != '':
print('test failed!')
elif trim('    ') != '':
print('test failed!')
else:
print('test successfully!')
``````

# 2.迭代：请使用迭代查找一个list中最小和最大值，并返回一个tuple

``````def findMinAndMax(L):
MIN=L[0]
MAX=L[0]
for i in L:
if i<MIN:
MIN=i
for j in L:
if j>MAX:
MAX=j
return (MIN,MAX)

# 测试
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!')
``````

# –– coding: utf-8 ––

L1 = [‘Hello’, ‘World’, 18, ‘Apple’, None]

# –-测试数据-–

print(L2)
if L2 == [‘hello’, ‘world’, ‘apple’]:
print(‘测试通过!’)
else:
print(‘测试失败!’)

# –-代码--：

``````def ListAndLower(s):
L2=[i.lower() for i in s if (isinstance(i,str))]
return L2

L1=['Hello','World',18,'Apple',None]#定义list L1

ListAndLower(L1)#调用函数

#测试
print(ListAndLower(L1))
if ListAndLower(L1) == ['hello', 'world', 'apple']:
print('test successfully!')
else:
print('test failed')

``````

image.png

原文作者：庭阶
原文地址: https://www.jianshu.com/p/44794c40c784
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。