Python 中的 str 是不可變序列,由Unicode 編碼點組成。
這些可能包含字母、變音符號、定位字元、數字、貨幣符號、emoji、標點符號、空格與換行字元,以及更多其他字元。
由於不可變,str 物件在記憶體中的值不會改變;看似會修改字串的方法,其實會回傳該 str 物件的新副本或新實例。
str 字面值可以用單引號'或雙引號"來宣告。需要時可以使用跳脫字元\。
>>> single_quoted = 'These allow "double quoting" without "escape" characters.'
>>> double_quoted = "These allow embedded 'single quoting', so you don't have to use an 'escape' character."
>>> escapes = 'If needed, a \'slash\' can be used as an escape character within a string when switching quote styles won\'t work.'
多行字串則用 ''' 或 """ 來宣告。
>>> triple_quoted = '''Three single quotes or "double quotes" in a row allow for multi-line string literals.
Line break characters, tabs and other whitespace are fully supported.
You\'ll most often encounter these as "doc strings" or "doc tests" written just below the first line of a function or class definition.
They\'re often used with auto documentation ✍ tools.
'''
字串可以用 + 運算子來串接。
這種做法應謹慎使用,因為它的效能不佳,也不容易維護。
language = "Ukrainian"
number = "nine"
word = "дев'ять"
sentence = word + " " + "means" + " " + number + " in " + language + "."
>>> print(sentence)
...
"дев'ять means nine in Ukrainian."
如果需要把 list、tuple、set 或其他由個別字串組成的集合合併成單一的 str,<str>.join(<iterable>) 會是更好的選擇:
# str.join() makes a new string from the iterables elements.
>>> chickens = ["hen", "egg", "rooster"] # Lists are iterable.
>>> ' '.join(chickens)
'hen egg rooster'
# Any string can be used as the joining element.
>>> ' :: '.join(chickens)
'hen :: egg :: rooster'
>>> ' 🌿 '.join(chickens)
'hen 🌿 egg 🌿 rooster'
# Any iterable can be used as input.
>>> flowers = ("rose", "daisy", "carnation") # Tuples are iterable.
>>> '*-*'.join(flowers)
'rose*-*daisy*-*carnation'
>>> flowers = {"rose", "daisy", "carnation"} # Sets are iterable, but output order is not guaranteed.
>>> '*-*'.join(flowers)
'rose*-*carnation*-*daisy'
>>> phrase = "This is my string" # Strings are iterable, but be careful!
>>> '..'.join(phrase)
'T..h..i..s.. ..i..s.. ..m..y.. ..s..t..r..i..n..g'
# Separators are inserted **between** elements, but can be any string (including spaces).
# This can be exploited for interesting effects.
>>> under_words = ['under', 'current', 'sea', 'pin', 'dog', 'lay']
>>> separator = ' ⤴️ under'
>>> separator.join(under_words)
'under ⤴️ undercurrent ⤴️ undersea ⤴️ underpin ⤴️ underdog ⤴️ underlay'
# The separator can be composed different ways, as long as the result is a string.
>>> upper_words = ['upper', 'crust', 'case', 'classmen', 'most', 'cut']
>>> separator = ' 🌟 ' + upper_words[0]
>>> separator.join(upper_words)
'upper 🌟 uppercrust 🌟 uppercase 🌟 upperclassmen 🌟 uppermost 🌟 uppercut'
str 中的編碼點可以用從左側算起的0-based index編號來存取:
creative = '창의적인'
>>> creative[0]
'창'
>>> creative[2]
'적'
>>> creative[3]
'인'
索引也可以從右側進行,從-1-based index開始:
creative = '창의적인'
>>> creative[-4]
'창'
>>> creative[-2]
'적'
>>> creative[-1]
'인'
Python 沒有獨立的「字元」或「rune」型別,因此對字串取索引會產生長度為 1 的新 str:
>>> website = "exercism"
>>> type(website[0])
<class 'str'>
>>> len(website[0])
1
>>> website[0] == website[0:1] == 'e'
True
子字串可以透過_切片表示法_選取,使用 <str>[<start>:stop:<step>] 產生新的字串。
結果不包含 stop 索引。
如果沒有指定 start,起始索引會是 0。
如果沒有指定 stop,stop 索引就會是字串的結尾。
moon_and_stars = '🌟🌟🌙🌟🌟⭐'
sun_and_moon = '🌞🌙🌞🌙🌞🌙🌞🌙🌞'
>>> moon_and_stars[1:4]
'🌟🌙🌟'
>>> moon_and_stars[:3]
'🌟🌟🌙'
>>> moon_and_stars[3:]
'🌟🌟⭐'
>>> moon_and_stars[:-1]
'🌟🌟🌙🌟🌟'
>>> moon_and_stars[:-3]
'🌟🌟🌙'
>>> sun_and_moon[::2]
'🌞🌞🌞🌞🌞'
>>> sun_and_moon[:-2:2]
'🌞🌞🌞🌞'
>>> sun_and_moon[1:-1:2]
'🌙🌙🌙🌙'
字串也可以透過 <str>.split(<separator>) 拆解成更小的字串,這會回傳由子字串組成的 list。
之後可以視需要對它進一步取索引或再拆分。
使用不帶任何引數的 <str>.split() 會以空白字元來拆分字串。
>>> cat_ipsum = "Destroy house in 5 seconds mock the hooman."
>>> cat_ipsum.split()
...
['Destroy', 'house', 'in', '5', 'seconds', 'mock', 'the', 'hooman.']
>>> cat_ipsum.split()[-1]
'hooman.'
>>> cat_words = "feline, four-footed, ferocious, furry"
>>> cat_words.split(', ')
...
['feline', 'four-footed', 'ferocious', 'furry']
<str>.split() 的分隔符可以超過一個字元。
比對拆分位置時會使用整個字串。
>>> colors = """red,
orange,
green,
purple,
yellow"""
>>> colors.split(',\n')
['red', 'orange', 'green', 'purple', 'yellow']
字串支援所有常見序列操作。
個別的編碼點可以在迴圈中用 for item in <str> 逐一疊代。
索引_連同_項目則可以在迴圈中用 for index, item in enumerate(<str>) 逐一疊代。
>>> exercise = 'လေ့ကျင့်'
# Note that there are more code points than perceived glyphs or characters
>>> for code_point in exercise:
... print(code_point)
...
လ
ေ
့
က
ျ
င
်
့
# Using enumerate will give both the value and index position of each element.
>>> for index, code_point in enumerate(exercise):
... print(index, ": ", code_point)
...
0 : လ
1 : ေ
2 : ့
3 : က
4 : ျ
5 : င
6 : ်
7 : ့
你正在幫妹妹寫英文詞彙作業,她覺得這份作業非常乏味。 她的班級正在學著用加上_前綴_和_後綴_的方式來造新詞。 老師會給一組單字,要學生把前綴加在字首、或把後綴加在字尾,拼寫正確地造出變化後的單字。
這份作業有四個活動,每個活動都有一組要處理的文字或單字。
un是英文裡最常見的前綴之一,意思是「不」。
在這個活動中,妹妹要透過加上un,造出否定的、也就是帶有「不」的意思的單字。
請實作add_prefix_un(<word>)函式,它接受word參數,並回傳加上un前綴後的新單字:
>>> add_prefix_un("happy")
'unhappy'
>>> add_prefix_un("manageable")
'unmanageable'
妹妹的班級還在學另外四個常見的前綴:
en(意思是「放入」或「覆蓋」)、
pre(意思是「之前」或「往前」)、
auto(意思是「自己」或「相同」)、
以及inter(意思是「之間」或「之中」)。
在這項練習中,班上會用這些前綴造出詞彙單字群組,方便一起學習。 每個前綴都會搭配一份常用單字清單。 學生要把前綴套用到每個單字上,並產生一個能顯示套用結果的字串。
請實作make_word_groups(<vocab_words>)函式,它接受格式如下的vocab_words參數:
[<prefix>, <word_1>, <word_2> .... <word_n>],並回傳一個字串,其中每個單字都套用了前綴,格式如下:
'<prefix> :: <prefix><word_1> :: <prefix><word_2> :: <prefix><word_n>'。
這裡不需要建立for或while迴圈來處理輸入。
好好想想,改用哪些字串方法(以及分隔符號)就能做到。
>>> make_word_groups(['en', 'close', 'joy', 'lighten'])
'en :: enclose :: enjoy :: enlighten'
>>> make_word_groups(['pre', 'serve', 'dispose', 'position'])
'pre :: preserve :: predispose :: preposition'
>> make_word_groups(['auto', 'didactic', 'graph', 'mate'])
'auto :: autodidactic :: autograph :: automate'
>>> make_word_groups(['inter', 'twine', 'connected', 'dependent'])
'inter :: intertwine :: interconnected :: interdependent'
ness是常見的後綴,意思是_「狀態」_。
在這個活動中,妹妹要移除ness後綴,找出原本的字根。
不過當然還是有些惱人的拼字規則:如果字根原本是以子音加上 'y' 結尾,那個 'y' 就會變成 'i'。
移除 'ness' 時,就得把這些字根裡的 'y' 還原回來。例如happiness --> happi --> happy。
請實作remove_suffix_ness(<word>)函式,它接受一個word,並回傳移除ness後綴後的字根。
>>> remove_suffix_ness("heaviness")
'heavy'
>>> remove_suffix_ness("sadness")
'sad'
後綴常用來改變一個單字所屬的詞性。
英文裡有個常見的做法叫「verbing」或「verbifying」,也就是加上en後綴,讓形容詞_變成_動詞。
在這項任務中,妹妹要練習「verbing」這種做法:從句子裡挑出形容詞,再把它變成動詞。 還好,這裡需要轉換的單字都是「規則」的:加上後綴時不需要改變拼字。
請實作adjective_to_verb(<sentence>, <index>)函式,它接受兩個參數。
一個使用該詞彙單字的sentence,以及該句子切開後該單字的index。
函式要回傳擷取出來的形容詞,並轉成動詞。
>>> adjective_to_verb('I need to make that bright.', -1 )
'brighten'
>>> adjective_to_verb('It got dark as the sun set.', 2)
'darken'