軌道
/
Python
Python
/
課程大綱
/
字串方法
字串

字串方法 在 Python

60 個練習

關於 字串方法

str 是不可變序列,由 Unicode 碼位組成。 其中可能包含字母、變音符號、位置標記字元、數字、貨幣符號、emoji、標點符號、空格與換行,以及其他更多內容。

字串實作了所有常見序列操作,並且可以用for item in <str>或for index, item in enumerate(<str>)語法來疊代。 個別碼位(長度為 1 的字串)可以從左邊以0-based index編號取得,或從右邊以-1-based index編號取得。

字串可以用<str> + <other str>或<str>.join(<iterable>)串接,並透過<str>.split(<separator>)分割。 它們也提供其他多種格式化與組合的選項。

為了進一步處理字串,Python 提供了豐富的字串方法,可用於搜尋、清理、轉換、翻譯,以及許多其他操作。

一些較常用的str方法包括:

  • 用<str>.startswith(<substr>)和<str>.endswith(<substr>)檢查前綴與後綴
  • 用<str>.title()、<str>.upper()/<str>.lower()和<str>.swapcase()之類的方法改變字串大小寫
  • 用<str>.strip(<chars>)、<str>.lstrip(<chars>)或<str>.rstrip(<chars>)移除字串開頭或結尾的字元
  • 用<str>.replace(<old>, <new>)方法取代子字串

str物件是_不可變_的,所以它在記憶體中的值無法改變;看似會修改字串的方法,其實會回傳該str物件的新複本或新實例。

<str>.endswith(<suffix>)會在字串以<suffix>結尾時回傳True,否則回傳False。

>>> 'My heart breaks. 💔'.endswith('💔')
True

>>> 'cheerfulness'.endswith('ness')
True

# Punctuation is part of the string, so needs to be included in any endswith match.
>>> 'Do you want to 💃?'.endswith('💃')
False

>>> 'The quick brown fox jumped over the lazy dog.'.endswith('dog')
False

<str>.title()會剖析字串,並把找到的每個「單字」的第一個「字元」變成大寫。 在 Python 中,這非常取決於所使用的語言編解碼器,以及該特定語言如何表示單字和字元。 某個語言或字元集也可能有地區設定規則。

>>> man_in_hat_th = 'ผู้ชายใส่หมวก'
>>> man_in_hat_ru = 'мужчина в шляпе'
>>> man_in_hat_ko = '모자를 쓴 남자'
>>> man_in_hat_en = 'the man in the hat.'

>>> man_in_hat_th.title()
'ผู้ชายใส่หมวก'

>>> man_in_hat_ru.title()
'Мужчина В Шляпе'

>>> man_in_hat_ko.title()
'모자를 쓴 남자'

>> man_in_hat_en.title()
'The Man In The Hat.'

<str>.strip(<chars>)會回傳一份str複本,並移除開頭與結尾的<chars>。 指定在<chars>中的碼位並不是前綴或後綴。所有組合的這些碼位都會從字串的兩端開始移除。 如果沒有為<chars>指定任何內容,就會移除所有組合的空白碼位。 如果只想移除左側或右側,可以使用<str>.lstrip(<chars>)和<str>.rstrip(<chars>)。

# This will remove "https://", because it can be formed from "/stph:". 
>>> 'https://unicode.org/emoji/'.strip('/stph:')
'unicode.org/emoji'

# Removal of all whitespace from both ends of the str.
>>> '   🐪🐪🐪🌟🐪🐪🐪   '.strip()
'🐪🐪🐪🌟🐪🐪🐪'

>>> justification = 'оправдание'
>>> justification.strip('еина')
'оправд'

# Prefix and suffix in one step.
>>> 'unaddressed'.strip('dnue')
'address'

>>> '  unaddressed  '.strip('dnue ')
'address'

<str>.replace(<substring>, <replacement substring>)會回傳一份字串複本,並把出現的<substring>全都取代成<replacement substring>。

以下引用的詩句出自 Lewis Carroll 的 The Hunting of the Snark

# The Hunting of the Snark, by Lewis Carroll
>>> quote = '''
"Just the place for a Snark!" the Bellman cried,
   As he landed his crew with care;
Supporting each man on the top of the tide
   By a finger entwined in his hair.

"Just the place for a Snark! I have said it twice:
   That alone should encourage the crew.
Just the place for a Snark! I have said it thrice:
   What I tell you three times is true."
'''

>>> quote.replace('Snark', '🐲')
...
'\n"Just the place for a 🐲!" the Bellman cried,\n   As he landed his crew with care;\nSupporting each man on the top of the tide\n   By a finger entwined in his hair.\n\n"Just the place for a 🐲! I have said it twice:\n   That alone should encourage the crew.\nJust the place for a 🐲! I have said it thrice:\n   What I tell you three times is true."\n'

>>> 'bookkeeper'.replace('kk', 'k k')
'book keeper'

🌟Python 3.9 新增

Python 3.9 導入了兩個新的字串方法,讓移除前綴和後綴變得容易許多。

<str>.removeprefix(<substring>)會回傳移除前綴後的字串(string[len(<substring>):])。如果<substring>不存在,就會回傳原始字串的複本。

# removing a prefix
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'bookkeeper'.removeprefix('book')
'keeper'

<str>.removesuffix(<substring>)會回傳移除後綴後的字串(string[:-len(substring)])。如果<substring>不存在,就會回傳原始字串的複本。

# removing a suffix
>>> 'TestHook'.removesuffix('Hook')
'Test'
>>> 'bookkeeper'.removesuffix('keeper')
'book'

想看更多範例和方法,非正式教學是不錯的起點。 Python 文件中的 How to Unicode詳細介紹了 Unicode、編碼、位元組,以及在 Python 中處理字串的其他技術細節。

Python 也透過re模組支援正規表達式,這會在之後的概念中介紹。

透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 字串方法

練習已鎖定

再解鎖 3 個練習,就能練習 字串方法