6–6. 字符串.創(chuàng)建一個(gè) string.strip()的替代函數(shù):接受一個(gè)字符串,去掉它前面和后面的 空格(如果使用 string.*strip()函數(shù)那本練習(xí)就沒(méi)有意義了)
1 'Take a string and remove all leading and trailing whitespace' 2 3 def newStrip(str): 4 'delete blanks around a string' 5 _end = len(str) 6 _start = 0 7 8 # delete the blanks at the beginning of the string 9 for i in range(_end):10 if str[i] != ' ':11 _start = i12 break 13 else:14 PRint 'invalid: The string is a blank string.' # if the string is a 15 _blank = True # blank string16 17 18 # delete the blanks in the end of the string19 for i in range(-1, _start - _end, -1):20 if str[i] != ' ':21 _end = _end + i22 break 23 if not _blank:24 print '-' + str[_start: _end] + '-' # print '-' make sure the function work25 26 # test27 if __name__ == '__main__':28 newStrip(raw_input('Enter a string: '))
6–7. 調(diào)試.看一下在例 6.5 中給出的代碼(buggy.py)
(a)研究這段代碼并
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注