文本
除了數字 Python 還可以操作文本(由?str?類型表示,稱為“字符串”)。 這包括字符 "!
", 單詞 "rabbit
", 名稱 "Paris
", 句子 "Got?your?back.
" 等等. "Yay!?:)
"。 它們可以用成對的單引號 ('...'
) 或雙引號 ("..."
) 來標示,結果完全相同?2。
>>>
>>> 'spam eggs' # single quotes 'spam eggs' >>> "Paris rabbit got your back :)! Yay!" # double quotes 'Paris rabbit got your back :)! Yay!' >>> '1975' # digits and numerals enclosed in quotes are also strings '1975'
要標示引號本身,我們需要對它進行“轉義”,即在前面加一個?\
。 或者,我們也可以使用不同類型的引號:
>>>
>>> 'doesn\'t' # use \' to escape the single quote... "doesn't" >>> "doesn't" # ...or use double quotes instead "doesn't" >>> '"Yes," they said.' '"Yes," they said.' >>> "\"Yes,\" they said." '"Yes," they said.' >>> '"Isn\'t," they said.' '"Isn\'t," they said.'
在 Python shell 中,字符串定義和輸出字符串看起來可能不同。?print()?函數會略去標示用的引號,并打印經過轉義的特殊字符,產生更為易讀的輸出:
>>>
>>> s = 'First line.\nSecond line.' # \n means newline >>> s # without print(), special characters are included in the string 'First line.\nSecond line.' >>> print(s) # with print(), special characters are interpreted, so \n produces new line First line. Second line.
如果不希望前置?\
?的字符轉義成特殊字符,可以使用?原始字符串,在引號前添加?r
?即可:
>>>
>>> print('C:\some\name') # here \n means newline! C:\some ame >>> print(r'C:\some\name') # note the r before the quote C:\some\name
原始字符串還有一個微妙的限制:一個原始字符串不能以奇數個?\
?字符結束;請參閱?此 FAQ 條目?了解更多信息及繞過的辦法。
字符串字面值可以包含多行。 一種實現方式是使用三重引號:"""..."""
?或?'''...'''
。 字符串中將自動包括行結束符,但也可以在換行的地方添加一個?\
?來避免此情況。 參見以下示例:
print("""\ Usage: thingy [OPTIONS]-h Display this usage message-H hostname Hostname to connect to """)
輸出如下(請注意開始的換行符沒有被包括在內):
Usage: thingy [OPTIONS]-h Display this usage message-H hostname Hostname to connect to
字符串可以用?+
?合并(粘到一起),也可以用?*
?重復:
>>>
>>> # 3 times 'un', followed by 'ium' >>> 3 * 'un' + 'ium' 'unununium'
相鄰的兩個或多個?字符串字面值?(引號標注的字符)會自動合并:
>>>
>>> 'Py' 'thon' 'Python'
拼接分隔開的長字符串時,這個功能特別實用:
>>>
>>> text = ('Put several strings within parentheses ' ... 'to have them joined together.') >>> text 'Put several strings within parentheses to have them joined together.'
這項功能只能用于兩個字面值,不能用于變量或表達式:
>>>
>>> prefix = 'Py' >>> prefix 'thon' # can't concatenate a variable and a string literalFile "<stdin>", line 1prefix 'thon'^^^^^^ SyntaxError: invalid syntax >>> ('un' * 3) 'ium'File "<stdin>", line 1('un' * 3) 'ium'^^^^^ SyntaxError: invalid syntax
合并多個變量,或合并變量與字面值,要用?+
:
>>>
>>> prefix + 'thon' 'Python'
字符串支持?索引?(下標訪問),第一個字符的索引是 0。單字符沒有專用的類型,就是長度為一的字符串:
>>>
>>> word = 'Python' >>> word[0] # character in position 0 'P' >>> word[5] # character in position 5 'n'
索引還支持負數,用負數索引時,從右邊開始計數:
>>>
>>> word[-1] # last character 'n' >>> word[-2] # second-last character 'o' >>> word[-6] 'P'
注意,-0 和 0 一樣,因此,負數索引從 -1 開始。
除了索引操作,還支持?切片。 索引用來獲取單個字符,而?切片?允許你獲取子字符串:
>>>
>>> word[0:2] # characters from position 0 (included) to 2 (excluded) 'Py' >>> word[2:5] # characters from position 2 (included) to 5 (excluded) 'tho'
切片索引的默認值很有用;省略開始索引時,默認值為 0,省略結束索引時,默認為到字符串的結尾:
>>>
>>> word[:2] # character from the beginning to position 2 (excluded) 'Py' >>> word[4:] # characters from position 4 (included) to the end 'on' >>> word[-2:] # characters from the second-last (included) to the end 'on'
注意,輸出結果包含切片開始,但不包含切片結束。因此,s[:i]?+?s[i:]
?總是等于?s
:
>>>
>>> word[:2] + word[2:] 'Python' >>> word[:4] + word[4:] 'Python'
還可以這樣理解切片,索引指向的是字符?之間?,第一個字符的左側標為 0,最后一個字符的右側標為?n?,n?是字符串長度。例如:
+---+---+---+---+---+---+| P | y | t | h | o | n |+---+---+---+---+---+---+0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1
第一行數字是字符串中索引 0...6 的位置,第二行數字是對應的負數索引位置。i?到?j?的切片由?i?和?j?之間所有對應的字符組成。
對于使用非負索引的切片,如果兩個索引都不越界,切片長度就是起止索引之差。例如,?word[1:3]
?的長度是 2。
索引越界會報錯:
>>>
>>> word[42] # the word only has 6 characters Traceback (most recent call last):File "<stdin>", line 1, in <module> IndexError: string index out of range
但是,切片會自動處理越界索引:
>>>
>>> word[4:42] 'on' >>> word[42:] ''
Python 字符串不能修改,是?immutable?的。因此,為字符串中某個索引位置賦值會報錯:
>>>
>>> word[0] = 'J' Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment >>> word[2:] = 'py' Traceback (most recent call last):File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
要生成不同的字符串,應新建一個字符串:
>>>
>>> 'J' + word[1:] 'Jython' >>> word[:2] + 'py' 'Pypy'
內置函數?len()?返回字符串的長度:
>>>
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34
參見
文本序列類型 --- str
字符串是?序列類型?,支持序列類型的各種操作。
字符串的方法
字符串支持很多變形與查找方法。
格式字符串字面值
內嵌表達式的字符串字面值。
格式字符串語法
使用?str.format()?格式化字符串。
printf 風格的字符串格式化
這里詳述了用?%
?運算符格式化字符串的操作。