除了數值,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'
>>> ''
''
兩個彼此相鄰的字元串文字自動連接配接:
>>> 'str' 'ing' #
'string'
>>> 'str'.strip() + 'ing' #
'string'
>>> 'str'.strip() 'ing' #
File "", 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 "", line 1, in ?
TypeError: object doesn't support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "", 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'