Python 字串方法備忘單
Python 字串操作的完整參考指南。掌握格式化、搜尋、拆分、取代和檢查字串屬性。
常見的字串格式化方法
用於改變字串大小寫、對齊方式和間距的方法。
| 方法/功能 | 文法 | 描述 |
|---|---|---|
| upper() | text.upper() | 將字串中的所有字元轉換為大寫。 |
| lower() | text.lower() | 將字串中的所有字元轉換為小寫。 |
| strip() | text.strip() | 刪除前導和尾隨空格。 |
| replace() | text.replace(old, new) | 將所有出現的子字串替換為另一個子字串。 |
字串搜尋和檢查
尋找索引、計算出現次數和檢查字串前綴/後綴的方法。
| 方法/功能 | 文法 | 描述 |
|---|---|---|
| find() | text.find(sub) | 如果找到則傳回子字串的最低索引,否則傳回 -1。 |
| count() | text.count(sub) | 傳回子字串不重疊出現的次數。 |
| startswith() | text.startswith(prefix) | 如果字串以指定前綴開頭,則傳回 True。 |
| endswith() | text.endswith(suffix) | 如果字串以指定後綴結尾,則傳回 True。 |
互動式簡報腳本
run_all_cheat_methods.py
在編輯器中執行# upper()
text.upper()
# lower()
text.lower()
# strip()
text.strip()
# replace()
text.replace(old, new)
# find()
text.find(sub)
# count()
text.count(sub)
# startswith()
text.startswith(prefix)
# endswith()
text.endswith(suffix)常見問題解答
字串方法會修改原始字串嗎?
不,Python 中的字串是不可變的。字串方法始終傳回一個新字串並保持原始字串不變。
find() 和index() 有什麼差別?
如果未找到子字串,find() 傳回 -1,而 index() 會引發 ValueError 異常。
相關主題
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。