使用方法操作字串
方法(method)是附加在物件上的特殊函式。某些資料型別具備方便操作資料的方法。例如,.upper() 方法會回傳字串的全大寫版本;.lower() 方法則會回傳字串的全小寫版本。
city = 'New York'
print(city.lower())
new york
另一個對字串非常好用的方法是 .format(),它會把字串中的大括號替換為傳入的引數。
city = 'New York'
print("City: {}".format(city))
City: New York
來練習用方法操作字串變數,同時學到一個有趣的美國歷史小知識吧!
本練習屬於課程
給 MATLAB 使用者的 Python
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Print the lowercase version of this Jeopardy clue
clue = 'Signer of the Dec. of Indep., framer of the Constitution of Mass., second President of the United States'
print(clue.____)