字符串 -- 不可改變的序列
如同大多數高級編程語言一樣,變長字符串是 Python 中的基本類型。Python 在“后臺”分配內存以保存字符串(或其它值),程序員不必為此操心。Python 還有一些其它高級語言沒有的字符串處理功能。
在 Python 中,字符串是“不可改變的序列”。盡管不能“按位置”修改字符串(如字節組),但程序可以引用字符串的元素或子序列,就象使用任何序列一樣。Python 使用靈活的“分片”操作來引用子序列,字符片段的格式類似于電子表格中一定范圍的行或列。以下交互式會話說明了字符串和字符片段的的用法:
字符串和分片
>>> s = "mary had a little lamb">>> s[0] # index is zero-based 'm'>>> s[3] = 'x' # changing element in-place failsTraceback (innermost last): File "<stdin>", line 1, in ?TypeError: object doesn't support item assignment>>> s[11:18] # 'slice' a subsequence 'little '>>> s[:4] # empty slice-begin assumes zero 'mary'>>> s[4] # index 4 is not included in slice [:4] ' '>>> s[5:-5] # can use "from end" index with negatives 'had a little'>>> s[:5]+s[5:] # slice-begin & slice-end are complimentary 'mary had a little lamb'
另一個功能強大的字符串操作就是簡單的 in 關鍵字。它提供了兩個直觀有效的構造:
in 關鍵字
>>> s = "mary had a little lamb">>> for c in s[11:18]: print c, # print each char in slice...l i t t l e>>> if 'x' in s: print 'got x' # test for char occurrence...>>> if 'y' in s: print 'got y' # test for char occurrence...got y
在 Python 中,有幾種方法可以構成字符串文字。可以使用單引號或雙引號,只要左引號和右引號匹配,常用的還有其它引號的變化形式。如果字符串包含換行符或嵌入引號,三重引號可以很方便地定義這樣的字符串,如下例所示:
三重引號的使用
>>> s2 = """Mary had a little lamb... its fleece was white as snow... and everywhere that Mary went... the lamb was sure to go""">>> print s2Mary had a little lambits fleece was white as snow and everywhere that Mary wentthe lamb was sure to go
使用單引號或三重引號的字符串前面可以加一個字母 "r" 以表示 Python 不應該解釋規則表達式特殊字符。例如:
使用 "r-strings"
>>> s3 = "this /n and /n that">>> print s3this and that>>> s4 = r "this /n and /n that">>> print s4this /n and /n that
新聞熱點
疑難解答