Day 1 :切片操作
Q:利用切片操作,實現一個函數trim(),去除字符串首尾的空格
思路:
通用方法:羅列所有處理數據-->每種數據的處理方法-->歸類方法並選擇合適的判斷循環語句-->測試所有組合的Testcase;
首先明確對於空格場景,所有字符串的形式和對應處理方法:
1、空字符串:[],通過if匹配,直接返回字符串本身;
2、首尾無空格:通過if匹配,直接返回字符串本身;
3、段首有空格:通過if匹配,a、統計段首所有空格數,返回切片值;b、逐一切片,利用迭代返回最終的切片值;
4、段尾有空格:通過else匹配,a、統計段尾所有空格數,返回切片值;b、逐一切片,利用迭代返回最終的切片值;
5、首尾均有空格:先匹配3,然后匹配4,即可得到結果;
a、方法在匹配' '場景時,無合適方法,代碼結構復雜度高,不考慮
判斷循環語句結構:
def trim(s):
if (s == " " or ( s[0] != " " and s[-1] != " " )): #匹配1、2場景;
elif (s[0] == " "): #匹配3、5場景;
else(s[-1] == " "): #匹配4、5場景;
處理方法:
return s #匹配1、2場景;
return trim(s[1:]) #匹配3、5場景,利用迭代,逐一切片;
return trim(s[:-1]) #匹配4、5場景,利用迭代,逐一切片
Testcase:
1、''
2、'hello'
3、' hello'
4、'hello '
5、' hello '
最終code:
def trim(s):
if(len(s) == 0 or (s[0] != ' ' and s[-1] != ' ')):
return s
elif s[0] == ' ':
return trim(s[1:])
else:
return trim(s[:-1])
if __name__ == '__main__':
if trim('hello ') != 'hello':
test = trim('hello ')
print test,'a'
print('測試失敗!')
elif trim(' hello') != 'hello':
test = trim(' hello')
print test,'b'
print('測試失敗!')
elif trim(' hello ') != 'hello':
test = trim(' hello ')
print test,'c'
print('測試失敗!')
elif trim('') != '':
test = trim('')
print test,'d'
print('測試失敗!')
elif trim(' ') != '':
test = trim(' ')
print test,'e'
print('測試失敗!')
else:
print('測試成功!')
pass