學習軌道
/
Python
Python
/
練習
/
小妹的作文
小妹的作文

小妹的作文

學習練習

簡介

str 類別提供了許多實用的方法,用來操作與組合字串。 這些方法涵蓋搜尋、清理、分割、轉換、翻譯,以及許多其他技巧。

字串是 Unicode 碼位 的 序列:個別的「字元」或碼位(長度為 1 的字串)可以用從左邊算起的0-based index編號,或從右邊算起的-1-based index編號來取值。 字串支援所有常見的序列操作。

可以用for item in <str>或for index, item in enumerate(<str>)語法來疊代。 也可以用<str> + <other str>或<str>.join(<iterable>)來串接。

字串是_不可變的_,意思是記憶體中str物件的值無法改變。 對str進行操作的函式或方法(就是我們這裡正在學的這些)會回傳該str物件的新instance,而不會修改原本的str。

以下是一些 Python 字串方法的精選範例。 完整的清單請參閱 Python 文件中的 str 類別。

<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>.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>.strip(<chars>)會回傳str的副本,並移除開頭與結尾的<chars>。 <chars>中指定的碼位並不是前綴或後綴,字串兩端的碼位所有組合都會被移除。 如果沒有為<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'

說明

在這道練習中,你要幫妹妹校訂她的學校報告。老師希望報告有正確的標點、文法,以及出色的用字遣詞。

你有四項任務,要清理並修改字串。

1. 將報告標題改成大寫

一篇好的報告需要格式正確的標題。 實作函式capitalize_title(<title>),它接受標題str作為參數,並將每個單字的第一個字母改成大寫。 這個函式應該回傳標題格式的str。

>>> capitalize_title("my hobbies")
"My Hobbies"

2. 檢查每個句子是否以句號結尾

你想確保報告的標點完美無誤。 實作函式check_sentence_ending(),它接受sentence作為參數。這個函式應該回傳bool。

>>> check_sentence_ending("I like to hike, bake, and read.")
True

3. 清理多餘的空格

為了讓報告看起來專業,必須移除多餘的空格。 實作函式clean_up_spacing(),它接受sentence作為參數。 這個函式應該移除句子開頭和結尾多餘的空白,並回傳更新後的新句子str。

>>> clean_up_spacing(" I like to go on hikes with my dog.  ")
"I like to go on hikes with my dog."

4. 用同義詞取代單字

為了讓報告_更上一層樓_,你可以把一些形容詞換成同義詞。 撰寫函式replace_word_choice(),它接受sentence、old_word和new_word作為參數。 這個函式應該把所有出現的old_word都取代成new_word,並回傳含有更新後句子的新str。

>>> replace_word_choice("I bake good cakes.", "good", "amazing")
"I bake amazing cakes."
透過 GitHub 編輯 連結會在新視窗或分頁中開啟
Python Exercism

準備好開始 小妹的作文 了嗎?

註冊 Exercism,透過 17 個概念146 個練習 和真人引導來學習並精通 Python,全部免費。