加入關鍵字引數
關鍵字引數在文字處理函式中特別實用,因為它能讓你指定可選的轉換,同時保持呼叫語句的可讀性。透過使用預設引數,你可以定義最常見的行為(例如轉成小寫),並在需要時仍允許使用者覆寫。
在這個練習中,你將建立一個 clean_text() 函式,用來將空白替換為底線,並可選擇性地將文字轉為小寫。
本練習屬於課程
Intermediate Python for Developers
練習說明
- 定義
clean_text()函式,參數為text與lower(預設值為True)。 - 在
else區塊中套用小寫轉換。 - 以引數
product呼叫clean_text()函式,測試其預設行為。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
product = 'Wireless Mouse'
# Define clean_text function
def clean_text(____, ____=____):
clean_text = text.replace(' ', '_')
if lower == False:
return clean_text
else:
# Apply lowercase transformation
return clean_text.____()
# Test with default behavior
print(____(____))