Python是一門功能強大且廣泛應用的編程語言,而對于許多開發(fā)者來說,字符串處理是Python編程中的一個核心部分。
一、引號標示字符串
Python可以操作文本,也就是字符串(str類型)。字符串可以包含各種字符,例如標點符號、單詞、名稱和句子等。在Python中,字符串可以使用成對的單引號或雙引號來標示,兩者的結果完全相同。
>>>'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'
為了標示引號本身,我們需要用反斜杠進行轉(zhuǎn)義,即在前面加一個 \,或使用另一種引號類型:
>>>'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() 函數(shù)時,引號會被省略,并且特殊字符會被解釋為換行符等特殊用途,產(chǎn)生更易讀的輸出:
>>>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.
如果不想讓前置 \的字符轉(zhuǎn)義成特殊字符,可以使用原始字符串,在引號前加上 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
原始字符串有一個微妙的限制:一個原始字符串不能以奇數(shù)個 \ 字符結束
字符串字面值可以包含多行內(nèi)容。一種實現(xiàn)方式是使用三重引號: “””…””” 或 ”’…”’ 。在字符串中會自動包含行結束符,但也可以在換行處使用`\`來避免這種情況。例如:
print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """)
輸出如下(注意開始的換行符沒有被包括在內(nèi)):
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 literal File "<stdin>", line 1 prefix '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'
索引還支持負數(shù),用負數(shù)索引時表示從右邊開始計數(shù):
>>>word[-1] # last character 'n' >>>word[-2] # second-last character 'o' >>>word[-6] 'P'
注意:-0 和 0 是一樣的,因此負數(shù)索引從 -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
第一行數(shù)字表示字符串中索引 0…6 的位置,第二行數(shù)字表示對應的負數(shù)索引位置。切片 [i:j] 由 i 和 j 之間所有對應的字符組成。對于使用非負索引的切片,如果兩個索引都未越界,則切片的長度是結束索引減去開始索引。例如,word[1:3] 的長度是2。
如果索引越界則會引發(fā)錯誤:
>>>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
要生成一個不同的字符串,需要創(chuàng)建一個新的字符串:
>>>'J' + word[1:] 'Jython' >>>word[:2] + 'py' 'Pypy'
內(nèi)置函數(shù) len() 可以返回字符串的長度:
>>> s = 'supercalifragilisticexpialidocious' >>> len(s) 34