1. 程式人生 > 實用技巧 >python每日一練:利用切片操作,實現一個trim()函式,去除字串首尾的空格,注意不要呼叫str的strip()方法

python每日一練:利用切片操作,實現一個trim()函式,去除字串首尾的空格,注意不要呼叫str的strip()方法

本文內容皆為作者原創,碼字不易,如需轉載,請註明出處:https://www.cnblogs.com/temari/p/13411894.html

最近在跟著廖雪峰老師的官方網站學習python,廖老師的教程講解的很細緻,每章課後會佈置一道練習題,用於鞏固本章學習的知識點,因此想到使用部落格記錄下每次練習的作業,也是對自己學習成果的檢測。

一,本次章節學習內容:

切片

二,本章課後作業:

題目:利用切片操作,實現一個trim()函式,去除字串首尾的空格,注意不要呼叫str的strip()方法

三,作業程式碼實現
# -*- coding: utf-8 -*-
def trim(s):
    t=""
#去掉首空格
    for i in range(len(s)):
        if s[i] !=' ':
            t=s[i:]
            break
#去掉末尾空格:判斷字串的長度,如果長度為0,不予操作,如果大於0,迴圈判斷列表的末尾是否為空格,是則刪除空格,直到末尾無空格,跳出迴圈
    if len(t)>0:
         while (t[-1] == ' '):
                t= t[:-1]
    print("尾空格去除:"+t+"|")
    return t
# 測試:
if trim('hello  ') != 'hello':
    print('1測試失敗!')
elif trim('  hello') != 'hello':
    print('2測試失敗!')
elif trim('  hello  ') != 'hello':
    print('3測試失敗!')
elif trim('  hello  world  ') != 'hello  world':
    print('4測試失敗!')
elif trim('') != '':
    print('5測試失敗!')
elif trim('    ') != '':
    print('6測試失敗!')
else:
    print('測試成功!')
四,程式碼演示