開始使用免費開始

加入關鍵字引數

關鍵字引數在文字處理函式中特別實用,因為它能讓你指定可選的轉換,同時保持呼叫語句的可讀性。透過使用預設引數,你可以定義最常見的行為(例如轉成小寫),並在需要時仍允許使用者覆寫。

在這個練習中,你將建立一個 clean_text() 函式,用來將空白替換為底線,並可選擇性地將文字轉為小寫。

本練習屬於課程

Intermediate Python for Developers

檢視課程

練習說明

  • 定義 clean_text() 函式,參數為 textlower(預設值為 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(____(____))
編輯並執行程式碼