除了數值,Python可以操作字串,它可以表現在以下幾個方面。包含在單引號或雙引號:
>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
字串可以寫多行。可以用\n表示,下一行是一個合乎邏輯的延續行,最後一個字元用反斜線:
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."
print hello
字串可以被包圍在一對三重引號裡面:
print """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
字串可以被串連在一起,用“+”運算子,重複*:
>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
兩個彼此相鄰的字串文字自動連接:
>>> 'str' 'ing' # <- This is ok
'string'
>>> 'str'.strip() + 'ing' # <- This is ok
'string'
>>> 'str'.strip() 'ing' # <- This is invalid
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
注意:word字串的內容是: “HelpA” 可以是下標(索引)和C一樣,字串的第一個字元下標(索引)0。可以指定的子串切片標誌來表示:兩個指數由冒號分隔。
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
切片索引可以使用預設值;前一個索引預設為零,第二個索引預設被切片的字串的大小。
>>> word[:2] # The first two characters
'He'
>>> word[2:] # Everything except the first two characters
'lpA'
和C字串不同,Python字串不能改變。想修改指定索引位置的字串會導致錯誤:
>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support slice assignment
然而,建立一個新的字串是簡單而有效:
>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'
這裡是一個有用的切片操作:[:]+[:]等於。
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
指數可以是負數,從右邊開始計數。例如:
>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # Everything except the last two characters
'Hel'