# Python 字符串
除了數字,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.'
```
Python中使用反斜杠轉義引號和其它特殊字符來準確地表示。
如果字符串包含有單引號但不含雙引號,則字符串會用雙引號括起來,否則用單引號括起來。對于這樣的輸入字符串,print() 函數會產生更易讀的輸出。
跨行的字面字符串可用以下幾種方法表示。使用續行符,即在每行最后一個字符后使用反斜線來說明下一行是上一行邏輯上的延續:
以下使用 \n 來添加新行:
```
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print('"Isn\'t," she said.')
"Isn't," she said.
>>> s = 'First line.\nSecond line.' # \n 意味著新行
>>> s # 不使用 print(), \n 包含在輸出中
'First line.\nSecond line.'
>>> print(s) # 使用 print(), \n 輸出一個新行
First line.
Second line.
```
以下使用 反斜線(\) 來續行:
```
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)
```
注意,其中的換行符仍然要使用 \n 表示——反斜杠后的換行符被丟棄了。以上例子將如下輸出:
```
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
```
或者,字符串可以被 """ (三個雙引號)或者 ''' (三個單引號)括起來。使用三引號時,換行符不需要轉義,它們會包含在字符串中。以下的例子使用了一個轉義符,避免在最開始產生一個不需要的空行。
```
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
```
如果我們使用"原始"字符串,那么 \n 不會被轉換成換行,行末的的反斜杠,以及源碼中的換行符,都將作為數據包含在字符串內。例如:
```
hello = r"This is a rather long string containing\n\
several lines of text much as you would do in C."
print(hello)
```
將會輸出:
```
This is a rather long string containing\n\
several lines of text much as you would do in C.
```
字符串可以使用 + 運算符串連接在一起,或者用 * 運算符重復:
```
>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
```
兩個緊鄰的字面字符串將自動被串連;上例的第一行也可以寫成 word = 'Help' 'A' ;這樣的操作只在兩個字面值間有效,不能隨意用于字符串表達式中:
```
>>> 'str' 'ing' # <- 這樣操作正確
'string'
>>> 'str'.strip() + 'ing' # <- 這樣操作正確
'string'
>>> 'str'.strip() 'ing' # <- 這樣操作錯誤
File "<stdin>", line 1, in ?
'str'.strip() 'ing'
^
SyntaxError: invalid syntax
```
字符串可以被索引;就像 C 語言一樣,字符串的第一個字符的索引為 0。沒有單獨的字符類型;一個字符就是長度為一的字符串。就像Icon編程語言一樣,子字符串可以使用分切符來指定:用冒號分隔的兩個索引。
```
>>> word[4]
'A'
>>> word[0:2]
'Hl'
>>> word[2:4]
'ep'
```
默認的分切索引很有用:默認的第一個索引為零,第二個索引默認為字符串可以被分切的長度。
```
>>> word[:2] # 前兩個字符
'He'
>>> word[2:] # 除了前兩個字符之外,其后的所有字符
'lpA'
```
不同于C字符串的是,Python字符串不能被改變。向一個索引位置賦值會導致錯誤:
```
>>> word[0] = 'x'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: 'str' object does not support slice assignment
```
然而,用組合內容的方法來創建新的字符串是簡單高效的:
```
>>> 'x' + word[1:]
'xelpA'
>>> 'Splat' + word[4]
'SplatA'
在分切操作字符串時,有一個很有用的規律: s[:i] + s[i:] 等于 s.
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
```
對于有偏差的分切索引的處理方式也很優雅:一個過大的索引將被字符串的大小取代,上限值小于下限值將返回一個空字符串。
```
>>> word[1:100]
'elpA'
>>> word[10:]
>>> word[2:1]
```
在索引中可以使用負數,這將會從右往左計數。例如:
```
>>> word[-1] # 最后一個字符
'A'
>>> word[-2] # 倒數第二個字符
'p'
>>> word[-2:] # 最后兩個字符
'pA'
>>> word[:-2] # 除了最后兩個字符之外,其前面的所有字符
'Hel'
但要注意, -0 和 0 完全一樣,所以 -0 不會從右開始計數!
>>> word[-0] # (既然 -0 等于 0)
'H'
```
超出范圍的負數索引會被截去多余部分,但不要嘗試在一個單元素索引(非分切索引)里使用:
```
>>> word[-100:]
'HelpA'
>>> word[-10] # 錯誤
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
```
有一個方法可以讓您記住分切索引的工作方式,想像索引是指向字符之間,第一個字符左邊的數字是 0。接著,有n個字符的字符串最后一個字符的右邊是索引n,例如:
```
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
```
第一行的數字 0...5 給出了字符串中索引的位置;第二行給出了相應的負數索引。分切部分從 i 到 j 分別由在邊緣被標記為 i 和 j 的全部字符組成。
對于非負數分切部分,如果索引都在有效范圍內,分切部分的長度就是索引的差值。例如, word[1:3] 的長度是2。
內置的函數 len() 用于返回一個字符串的長度:
```
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
```
- Python 基礎教程
- Python 簡介
- Python 環境搭建
- Python 基礎語法
- Python 變量類型
- Python 運算符
- Python 條件語句
- Python 循環語句
- Python While循環語句
- Python for 循環語句
- Python 循環嵌套
- Python break 語句
- Python continue 語句
- Python pass 語句
- Python 數字
- Python 字符串
- Python 列表(Lists)
- Python 元組
- Python 字典(Dictionary)
- Python 日期和時間
- Python 函數
- Python 模塊
- Python 文件I/O
- Python 異常處理
- Python 高級教程
- Python 面向對象
- Python 正則表達式
- Python CGI編程
- Python 使用SMTP發送郵件
- Python 多線程
- Python 2.x與3??.x版本區別
- Python IDE
- Python JSON
- Python3 教程
- Python3 基礎語法
- Python3 基本數據類型
- Python3 解釋器
- Python3 注釋
- Python3 數字運算
- Python3 字符串
- Python3 列表
- Python3 編程第一步
- Python3 條件控制
- Python3 循環
- Python3 函數
- Python3 數據結構
- Python3 模塊
- Python3 輸入和輸出
- Python3 錯誤和異常
- Python3 類
- Python3 標準庫概覽
- 免責聲明