### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](difflib.xhtml "模塊 difflib 是一個計算差異的助手") |
- [上一頁](string.xhtml "string --- 常見的字符串操作") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 標準庫](index.xhtml) ?
- [文本處理服務](text.xhtml) ?
- $('.inline-search').show(0); |
# [`re`](#module-re "re: Regular expression operations.") --- 正則表達式操作
**源代碼:** [Lib/re.py](https://github.com/python/cpython/tree/3.7/Lib/re.py) \[https://github.com/python/cpython/tree/3.7/Lib/re.py\]
- - - - - -
這個模塊提供了與 Perl 語言類似的正則表達式匹配操作。
模式和被搜索的字符串既可以是 Unicode 字符串 ([`str`](stdtypes.xhtml#str "str")) ,也可以是8位字節串 ([`bytes`](stdtypes.xhtml#bytes "bytes"))。 但是,Unicode 字符串與8位字節串不能混用:也就是說,你不能用一個字節串模式去匹配 Unicode 字符串,反之亦然;類似地,當進行替換操作時,替換字符串的類型也必須與所用的模式和搜索字符串的類型一致。
正則表達式使用反斜杠(`'\'`)來表示特殊形式,或者把特殊字符轉義成普通字符。 而反斜杠在普通的 Python 字符串里也有相同的作用,所以就產生了沖突。比如說,要匹配一個字面上的反斜杠,正則表達式模式不得不寫成 `'\\\\'`,因為正則表達式里匹配一個反斜杠必須是 `\\` ,而每個反斜杠在普通的 Python 字符串里都要寫成 `\\` 。
解決辦法是對于正則表達式樣式使用 Python 的原始字符串表示法;在帶有 `'r'` 前綴的字符串字面值中,反斜杠不必做任何特殊處理。 因此 `r"\n"` 表示包含 `'\'` 和 `'n'` 兩個字符的字符串,而 `"\n"` 則表示只包含一個換行符的字符串。 樣式在 Python 代碼中通常都會使用這種原始字符串表示法來表示。
絕大部分正則表達式操作都提供為模塊函數和方法,在 [編譯正則表達式](#re-objects). 這些函數是一個捷徑,不需要先編譯一個正則對象,但是損失了一些優化參數。
參見
第三方模塊 [regex](https://pypi.org/project/regex/) \[https://pypi.org/project/regex/\] , 提供了與標準庫 [`re`](#module-re "re: Regular expression operations.") 模塊兼容的API接口, 同時還提供了額外的功能和更全面的Unicode支持。
## 正則表達式語法
一個正則表達式(或RE)指定了一集與之匹配的字符串;模塊內的函數可以讓你檢查某個字符串是否跟給定的正則表達式匹配(或者一個正則表達式是否匹配到一個字符串,這兩種說法含義相同)。
正則表達式可以拼接; 如果 *A* 和 *B* 都是正則表達式, 那么 *AB* 也是正則表達式。 通常, 如果字符串 *p* 匹配 *A* 并且另一個字符串 *q* 匹配 *B*, 那么 *pq* 可以匹配 AB。除非 *A* 或者 *B* 包含低優先級操作,*A* 和 *B* 存在邊界條件;或者命名組引用。所以,復雜表達式可以很容易的從這里描述的簡單源語表達式構建。 了解更多正則表達式理論和實現,參考the Friedl book [\[Frie09\]](#frie09) ,或者其他編譯器構建的書籍。
以下是正則表達式格式的簡要說明。更詳細的信息和演示,參考 [正則表達式HOWTO](../howto/regex.xhtml#regex-howto)。
正則表達式可以包含普通或者特殊字符。絕大部分普通字符,比如 `'A'`, `'a'`, 或者 `'0'`,都是最簡單的正則表達式。它們就匹配自身。你可以拼接普通字符,所以 `last` 匹配字符串 `'last'`. (在這一節的其他部分,我們將用 `this special style` 這種方式表示正則表達式,通常不帶引號,要匹配的字符串用 `'in single quotes'` ,單引號形式。)
有些字符,比如 `'|'` 或者 `'('`,屬于特殊字符。 特殊字符既可以表示它的普通含義, 也可以影響它旁邊的正則表達式的解釋。
重復修飾符 (`*`, `+`, `?`, `{m,n}`, 等) 不能直接嵌套。這樣避免了非貪婪后綴 `?` 修飾符,和其他實現中的修飾符產生的多義性。要應用一個內層重復嵌套,可以使用括號。 比如,表達式 `(?:a{6})*` 匹配6個 `'a'` 字符重復任意次數。
特殊字符是:
`.`(點) 在默認模式,匹配除了換行的任意字符。如果指定了標簽 [`DOTALL`](#re.DOTALL "re.DOTALL") ,它將匹配包括換行符的任意字符。
`^`(插入符號) 匹配字符串的開頭, 并且在 [`MULTILINE`](#re.MULTILINE "re.MULTILINE") 模式也匹配換行后的首個符號。
`$`匹配字符串尾或者換行符的前一個字符,在 [`MULTILINE`](#re.MULTILINE "re.MULTILINE") 模式匹配換行符的前一個字符。 `foo` 匹配 `'foo'` 和 `'foobar'` , 但正則 `foo$` 只匹配 `'foo'`。更有趣的是, 在 `'foo1\nfoo2\n'` 搜索 `foo.$` ,通常匹配 `'foo2'` ,但在 [`MULTILINE`](#re.MULTILINE "re.MULTILINE") 模式 ,可以匹配到 `'foo1'` ;在 `'foo\n'` 搜索 `$` 會找到兩個空串:一個在換行前,一個在字符串最后。
`*`對它前面的正則式匹配0到任意次重復, 盡量多的匹配字符串。 `ab*` 會匹配 `'a'`, `'ab'`, 或者 `'a'``后面跟隨任意個 ``'b'`。
`+`對它前面的正則式匹配1到任意次重復。 `ab+` 會匹配 `'a'` 后面跟隨1個以上到任意個 `'b'`,它不會匹配 `'a'`。
`?`對它前面的正則式匹配0到1次重復。 `ab?` 會匹配 `'a'` 或者 `'ab'`。
`*?`, `+?`, `??``'*'`, `'+'`,和 `'?'` 修飾符都是 *貪婪的*;它們在字符串進行盡可能多的匹配。有時候并不需要這種行為。如果正則式 `<.*>` 希望找到 `'<a> b <c>'`,它將會匹配整個字符串,而不僅是 `'<a>'`。在修飾符之后添加 `?` 將使樣式以 *非貪婪`方式或者 :dfn:`最小* 方式進行匹配; 盡量 *少* 的字符將會被匹配。 使用正則式 `<.*?>` 將會僅僅匹配 `'<a>'`。
"{m}"對其之前的正則式指定匹配 *m* 個重復;少于 *m* 的話就會導致匹配失敗。比如, `a{6}` 將匹配6個 `'a'` , 但是不能是5個。
"{m, n}"對正則式進行 *m* 到 *n* 次匹配,在 *m* 和 *n* 之間取盡量多。 比如,`a{3,5}` 將匹配 3 到 5個 `'a'`。忽略 *m* 意為指定下界為0,忽略 *n* 指定上界為無限次。 比如 `a{4,}b` 將匹配 `'aaaab'` 或者1000個 `'a'` 尾隨一個 `'b'`,但不能匹配 `'aaab'`。逗號不能省略,否則無法辨別修飾符應該忽略哪個邊界。
`{m,n}?`前一個修飾符的非貪婪模式,只匹配盡量少的字符次數。比如,對于 `'aaaaaa'`, `a{3,5}` 匹配 5個 `'a'` ,而 `a{3,5}?` 只匹配3個 `'a'`。
`\`轉義特殊字符(允許你匹配 `'*'`, `'?'`, 或者此類其他),或者表示一個特殊序列;特殊序列之后進行討論。
如果你沒有使用原始字符串( `r'raw'` )來表達樣式,要牢記Python也使用反斜杠作為轉義序列;如果轉義序列不被Python的分析器識別,反斜杠和字符才能出現在字符串中。如果Python可以識別這個序列,那么反斜杠就應該重復兩次。這將導致理解障礙,所以高度推薦,就算是最簡單的表達式,也要使用原始字符串。
`[]`用于表示一個字符集合。在一個集合中:
- 字符可以單獨列出,比如 `[amk]` 匹配 `'a'`, `'m'`, 或者 `'k'`。
- 可以表示字符范圍,通過用 `'-'` 將兩個字符連起來。比如 `[a-z]` 將匹配任何小寫ASCII字符, `[0-5][0-9]` 將匹配從 `00` 到 `59` 的兩位數字, `[0-9A-Fa-f]` 將匹配任何十六進制數位。 如果 `-` 進行了轉義 (比如 `[a\-z]`)或者它的位置在首位或者末尾(如 `[-a]` 或 `[a-]`),它就只表示普通字符 `'-'`。
- 特殊字符在集合中,失去它的特殊含義。比如 `[(+*)]` 只會匹配這幾個文法字符 `'('`, `'+'`, `'*'`, or `')'`。
- 字符類如 `\w` 或者 `\S` (如下定義) 在集合內可以接受,它們可以匹配的字符由 [`ASCII`](#re.ASCII "re.ASCII") 或者 [`LOCALE`](#re.LOCALE "re.LOCALE") 模式決定。
- 不在集合范圍內的字符可以通過 *取反* 來進行匹配。如果集合首字符是 `'^'` ,所有 *不* 在集合內的字符將會被匹配,比如 `[^5]` 將匹配所有字符,除了 `'5'`, `[^^]` 將匹配所有字符,除了 `'^'`. `^` 如果不在集合首位,就沒有特殊含義。
- 在集合內要匹配一個字符 `']'`,有兩種方法,要么就在它之前加上反斜杠,要么就把它放到集合首位。比如, `[()[\]{}]` 和 `[]()[{}]` 都可以匹配括號。
- [Unicode Technical Standard #18](https://unicode.org/reports/tr18/) \[https://unicode.org/reports/tr18/\] 里的嵌套集合和集合操作支持可能在未來添加。這將會改變語法,所以為了幫助這個改變,一個 [`FutureWarning`](exceptions.xhtml#FutureWarning "FutureWarning") 將會在有多義的情況里被 `raise`,包含以下幾種情況,集合由 `'['` 開始,或者包含下列字符序列 `'--'`, `'&&'`, `'~~'`, 和 `'||'`。為了避免警告,需要將它們用反斜杠轉義。
在 3.7 版更改: 如果一個字符串構建的語義在未來會改變的話,一個 [`FutureWarning`](exceptions.xhtml#FutureWarning "FutureWarning") 會 `raise` 。
`|``A|B`, *A* 和 *B* 可以是任意正則表達式,創建一個正則表達式,匹配 *A* 或者 *B*. 任意個正則表達式可以用 `'|'` 連接。它也可以在組合(見下列)內使用。掃描目標字符串時, `'|'` 分隔開的正則樣式從左到右進行匹配。當一個樣式完全匹配時,這個分支就被接受。意思就是,一旦 *A* 匹配成功, *B* 就不再進行匹配,即便它能產生一個更好的匹配。或者說,`'|'` 操作符絕不貪婪。 如果要匹配 `'|'` 字符,使用 `\|`, 或者把它包含在字符集里,比如 `[|]`.
`(...)`(組合),匹配括號內的任意正則表達式,并標識出組合的開始和結尾。匹配完成后,組合的內容可以被獲取,并可以在之后用 `\number` 轉義序列進行再次匹配,之后進行詳細說明。要匹配字符 `'('` 或者 `')'`, 用 `\(` 或 `\)`, 或者把它們包含在字符集合里: `[(]`, `[)]`.
`(?…)`這是個擴展標記法 (一個 `'?'` 跟隨 `'('` 并無含義)。 `'?'` 后面的第一個字符決定了這個構建采用什么樣的語法。這種擴展通常并不創建新的組合; `(?P<name>...)` 是唯一的例外。 以下是目前支持的擴展。
`(?aiLmsux)`( `'a'`, `'i'`, `'L'`, `'m'`, `'s'`, `'u'`, `'x'` 中的一個或多個) 這個組合匹配一個空字符串;這些字符對正則表達式設置以下標記 [`re.A`](#re.A "re.A") (只匹配ASCII字符), [`re.I`](#re.I "re.I") (忽略大小寫), [`re.L`](#re.L "re.L") (語言依賴), [`re.M`](#re.M "re.M") (多行模式), [`re.S`](#re.S "re.S") (點dot匹配全部字符), `re.U` (Unicode匹配), and [`re.X`](#re.X "re.X") (冗長模式)。 (這些標記在 [模塊內容](#contents-of-module-re) 中描述) 如果你想將這些標記包含在正則表達式中,這個方法就很有用,免去了在 [`re.compile()`](#re.compile "re.compile") 中傳遞 *flag* 參數。標記應該在表達式字符串首位表示。
`(?:…)`正則括號的非捕獲版本。 匹配在括號內的任何正則表達式,但該分組所匹配的子字符串 *不能* 在執行匹配后被獲取或是之后在模式中被引用。
`(?aiLmsux-imsx:…)`(`'a'`, `'i'`, `'L'`, `'m'`, `'s'`, `'u'`, `'x'` 中的0或者多個, 之后可選跟隨 `'-'` 在后面跟隨 `'i'` , `'m'` , `'s'` , `'x'` 中的一到多個 .) 這些字符為表達式的其中一部分 *設置* 或者 *去除* 相應標記 [`re.A`](#re.A "re.A") (只匹配ASCII), [`re.I`](#re.I "re.I") (忽略大小寫), [`re.L`](#re.L "re.L") (語言依賴), [`re.M`](#re.M "re.M") (多行), [`re.S`](#re.S "re.S") (點匹配所有字符), `re.U` (Unicode匹配), and [`re.X`](#re.X "re.X") (冗長模式)。(標記描述在 [模塊內容](#contents-of-module-re) .)
`'a'`, `'L'` and `'u'` 作為內聯標記是相互排斥的, 所以它們不能結合在一起,或者跟隨 `'-'` 。 當他們中的某個出現在內聯組中,它就覆蓋了括號組內的匹配模式。在Unicode樣式中, `(?a:...)` 切換為 只匹配ASCII, `(?u:...)` 切換為Unicode匹配 (默認). 在byte樣式中 `(?L:...)` 切換為語言依賴模式, `(?a:...)` 切換為 只匹配ASCII (默認)。這種方式只覆蓋組合內匹配,括號外的匹配模式不受影響。
3\.6 新版功能.
在 3.7 版更改: 符號 `'a'`, `'L'` 和 `'u'` 同樣可以用在一個組合內。
`(?P<name>…)`(命名組合)類似正則組合,但是匹配到的子串組在外部是通過定義的 *name* 來獲取的。組合名必須是有效的Python標識符,并且每個組合名只能用一個正則表達式定義,只能定義一次。一個符號組合同樣是一個數字組合,就像這個組合沒有被命名一樣。
命名組合可以在三種上下文中引用。如果樣式是 `(?P<quote>['"]).*?(?P=quote)` (也就是說,匹配單引號或者雙引號括起來的字符串):
引用組合 "quote" 的上下文
引用方法
在正則式自身內
- `(?P=quote)` (如示)
- `\1`
處理匹配對象 *m*
- `m.group('quote')`
- `m.end('quote')` (等)
傳遞到 `re.sub()` 里的 *repl* 參數中
- `\g<quote>`
- `\g<1>`
- `\1`
`(?P=name)`反向引用一個命名組合;它匹配前面那個叫 *name* 的命名組中匹配到的串同樣的字串。
`(?#…)`注釋;里面的內容會被忽略。
`(?=…)`匹配 `…` 的內容,但是并不消費樣式的內容。這個叫做 *lookahead assertion*。比如, `Isaac (?=Asimov)` 匹配 `'Isaac '` 只有在后面是 `'Asimov'` 的時候。
`(?!…)`匹配 `…` 不符合的情況。這個叫 *negative lookahead assertion* (前視取反)。比如說, `Isaac (?!Asimov)` 只有后面 *不* 是 `'Asimov'` 的時候才匹配 `'Isaac '` 。
`(?<=…)`匹配字符串的當前位置,它的前面匹配 `…` 的內容到當前位置。這叫:dfn:positive lookbehind assertion (正向后視斷定)。 `(?<=abc)def` 會在 `'abcdef'` 中找到一個匹配,因為后視會往后看3個字符并檢查是否包含匹配的樣式。包含的匹配樣式必須是定長的,意思就是 `abc` 或 `a|b` 是允許的,但是 `a*` 和 `a{3,4}` 不可以。注意以 positive lookbehind assertions 開始的樣式,如 `(?<=abc)def` ,并不是從 a 開始搜索,而是從 d 往回看的。你可能更加愿意使用 [`search()`](#re.search "re.search") 函數,而不是 [`match()`](#re.match "re.match") 函數:
```
>>> import re
>>> m = re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'
```
這個例子搜索一個跟隨在連字符后的單詞:
```
>>> m = re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'
```
在 3.5 版更改: 添加定長組合引用的支持。
`(?<!…)`匹配當前位置之前不是 `…` 的樣式。這個叫:dfn:negative lookbehind assertion (后視斷定取非)。類似正向后視斷定,包含的樣式匹配必須是定長的。由 negative lookbehind assertion 開始的樣式可以從字符串搜索開始的位置進行匹配。
`(?(id/name)yes-pattern|no-pattern)`如果給定的 *id* 或 *name* 存在,將會嘗試匹配 `yes-pattern` ,否則就嘗試匹配 `no-pattern`,`no-pattern` 可選,也可以被忽略。比如, `(<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$)` 是一個email樣式匹配,將匹配 `'<user@host.com>'` 或 `'user@host.com'` ,但不會匹配 `'<user@host.com'` ,也不會匹配 `'user@host.com>'`。
由 `'\'` 和一個字符組成的特殊序列在以下列出。 如果普通字符不是ASCII數位或者ASCII字母,那么正則樣式將匹配第二個字符。比如,`\$` 匹配字符 `'$'`.
`\number`匹配數字代表的組合。每個括號是一個組合,組合從1開始編號。比如 `(.+) \1` 匹配 `'the the'` 或者 `'55 55'`, 但不會匹配 `'thethe'` (注意組合后面的空格)。這個特殊序列只能用于匹配前面99個組合。如果 *number* 的第一個數位是0, 或者 *number* 是三個八進制數,它將不會被看作是一個組合,而是八進制的數字值。在 `'['` 和 `']'` 字符集合內,任何數字轉義都被看作是字符。
`\A`只匹配字符串開始。
`\b`匹配空字符串,但只在單詞開始或結尾的位置。一個單詞被定義為一個單詞字符的序列。注意,通常 `\b` 定義為 `\w` 和 `\W` 字符之間,或者 `\w` 和字符串開始/結尾的邊界, 意思就是 `r'\bfoo\b'` 匹配 `'foo'`, `'foo.'`, `'(foo)'`, `'bar foo baz'` 但不匹配 `'foobar'` 或者 `'foo3'`。
默認情況下,Unicode字母和數字是在Unicode樣式中使用的,但是可以用 [`ASCII`](#re.ASCII "re.ASCII") 標記來更改。如果 [`LOCALE`](#re.LOCALE "re.LOCALE") 標記被設置的話,詞的邊界是由當前語言區域設置決定的,`\b` 表示退格字符,以便與Python字符串文本兼容。
`\B`匹配空字符串,但 *不* 能在詞的開頭或者結尾。意思就是 `r'py\B'` 匹配 `'python'`, `'py3'`, `'py2'`, 但不匹配 `'py'`, `'py.'`, 或者 `'py!'`. `\B` 是 `\b` 的取非,所以Unicode樣式的詞語是由Unicode字母,數字或下劃線構成的,雖然可以用 [`ASCII`](#re.ASCII "re.ASCII") 標志來改變。如果使用了 [`LOCALE`](#re.LOCALE "re.LOCALE") 標志,則詞的邊界由當前語言區域設置。
`\d`對于 Unicode (str) 樣式:匹配任何Unicode十進制數(就是在Unicode字符目錄\[Nd\]里的字符)。這包括了 `[0-9]` ,和很多其他的數字字符。如果設置了 [`ASCII`](#re.ASCII "re.ASCII") 標志,就只匹配 `[0-9]` 。
對于8位(bytes)樣式:匹配任何十進制數,就是 `[0-9]`。
`\D`匹配任何非十進制數字的字符。就是 `\d` 取非。 如果設置了 [`ASCII`](#re.ASCII "re.ASCII") 標志,就相當于 `[^0-9]` 。
`\s`對于 Unicode (str) 樣式:匹配任何Unicode空白字符(包括 `[ \t\n\r\f\v]` ,還有很多其他字符,比如不同語言排版規則約定的不換行空格)。如果 [`ASCII`](#re.ASCII "re.ASCII") 被設置,就只匹配 `[ \t\n\r\f\v]` 。
對于8位(bytes)樣式:匹配ASCII中的空白字符,就是 `[ \t\n\r\f\v]` 。
`\S`匹配任何非空白字符。就是 `\s` 取非。如果設置了 [`ASCII`](#re.ASCII "re.ASCII") 標志,就相當于 `[^ \t\n\r\f\v]` 。
`\w`對于 Unicode (str) 樣式:匹配Unicode詞語的字符,包含了可以構成詞語的絕大部分字符,也包括數字和下劃線。如果設置了 [`ASCII`](#re.ASCII "re.ASCII") 標志,就只匹配 `[a-zA-Z0-9_]` 。
對于8位(bytes)樣式:匹配ASCII字符中的數字和字母和下劃線,就是 `[a-zA-Z0-9_]` 。如果設置了 [`LOCALE`](#re.LOCALE "re.LOCALE") 標記,就匹配當前語言區域的數字和字母和下劃線。
`\W`匹配任何非詞語字符。是 `\w` 取非。如果設置了 [`ASCII`](#re.ASCII "re.ASCII") 標記,就相當于 `[^a-zA-Z0-9_]` 。如果設置了 [`LOCALE`](#re.LOCALE "re.LOCALE") 標志,就匹配當前語言區域的 *非* 詞語字符。
`\Z`只匹配字符串尾。
絕大部分Python的標準轉義字符也被正則表達式分析器支持。:
```
\a \b \f \n
\r \t \u \U
\v \x \\
```
(注意 `\b` 被用于表示詞語的邊界,它只在字符集合內表示退格,比如 `[\b]` 。)
`'\u'` 和 `'\U'` 轉義序列只在 Unicode 樣式中支持。 在 bytes 算啊看會顯示錯誤。 未知的 ASCII 字符轉義序列保留在未來使用,會被當作錯誤來處理。
八進制轉義包含為一個有限形式。如果首位數字是 0, 或者有三個八進制數位,那么就認為它是八進制轉義。其他的情況,就看作是組引用。對于字符串文本,八進制轉義最多有三個數位長。
在 3.3 版更改: 增加了 `'\u'` 和 `'\U'` 轉義序列。
在 3.6 版更改: 由 `'\'` 和一個ASCII字符組成的未知轉義會被看成錯誤。
## 模塊內容
模塊定義了幾個函數,常量,和一個例外。有些函數是編譯后的正則表達式方法的簡化版本(少了一些特性)。絕大部分重要的應用,總是會先將正則表達式編譯,之后在進行操作。
在 3.6 版更改: 標志常量現在是 `RegexFlag` 類的實例,這個類是 [`enum.IntFlag`](enum.xhtml#enum.IntFlag "enum.IntFlag") 的子類。
`re.``compile`(*pattern*, *flags=0*)將正則表達式的樣式編譯為一個 [正則表達式對象](#re-objects) (正則對象),可以用于匹配,通過這個對象的方法 [`match()`](#re.Pattern.match "re.Pattern.match"), [`search()`](#re.Pattern.search "re.Pattern.search") 以及其他如下描述。
這個表達式的行為可以通過指定 *標記* 的值來改變。值可以是以下任意變量,可以通過位的OR操作來結合( `|` 操作符)。
序列
```
prog = re.compile(pattern)
result = prog.match(string)
```
等價于
```
result = re.match(pattern, string)
```
如果需要多次使用這個正則表達式的話,使用 [`re.compile()`](#re.compile "re.compile") 和保存這個正則對象以便復用,可以讓程序更加高效。
注解
通過 [`re.compile()`](#re.compile "re.compile") 編譯后的樣式,和模塊級的函數會被緩存, 所以少數的正則表達式使用無需考慮編譯的問題。
`re.``A``re.``ASCII`讓 `\w`, `\W`, `\b`, `\B`, `\d`, `\D`, `\s` 和 `\S` 只匹配ASCII,而不是Unicode。這只對Unicode樣式有效,會被byte樣式忽略。相當于前面語法中的內聯標志 `(?a)` 。
注意,為了保持向后兼容, `re.U` 標記依然存在(還有他的同義 `re.UNICODE` 和嵌入形式 `(?u)` ) , 但是這些在 Python 3 是冗余的,因為默認字符串已經是Unicode了(并且Unicode匹配不允許byte出現)。
`re.``DEBUG`顯示編譯時的debug信息,沒有內聯標記。
`re.``I``re.``IGNORECASE`進行忽略大小寫匹配;表達式如 `[A-Z]` 也會匹配小寫字符。Unicode匹配(比如 `ü` 匹配 `ü`)同樣有用,除非設置了 [`re.ASCII`](#re.ASCII "re.ASCII") 標記來禁用非ASCII匹配。當前語言區域不會改變這個標記,除非設置了 [`re.LOCALE`](#re.LOCALE "re.LOCALE") 標記。這個相當于內聯標記 `(?i)` 。
注意,當設置了 [`IGNORECASE`](#re.IGNORECASE "re.IGNORECASE") 標記,搜索Unicode樣式 `[a-z]` 或 `[A-Z]` 的結合時,它將會匹配52個ASCII字符和4個額外的非ASCII字符: '?' (U+0130, 拉丁大寫的 I 帶個點在上面), '?' (U+0131, 拉丁小寫沒有點的 I ), '?' (U+017F, 拉丁小寫長 s) and 'K' (U+212A, 開爾文符號).如果使用 [`ASCII`](#re.ASCII "re.ASCII") 標記,就只匹配 'a' 到 'z' 和 'A' 到 'Z' 。
`re.``L``re.``LOCALE`由當前語言區域決定 `\w`, `\W`, `\b`, `\B` 和大小寫敏感匹配。這個標記只能對byte樣式有效。這個標記不推薦使用,因為語言區域機制很不可靠,它一次只能處理一個 "習慣”,而且只對8位字節有效。Unicode匹配在Python 3 里默認啟用,并可以處理不同語言。 這個對應內聯標記 `(?L)` 。
在 3.6 版更改: [`re.LOCALE`](#re.LOCALE "re.LOCALE") 只能用于byte樣式,而且不能和 [`re.ASCII`](#re.ASCII "re.ASCII") 一起用。
在 3.7 版更改: 設置了 [`re.LOCALE`](#re.LOCALE "re.LOCALE") 標記的編譯正則對象不再在編譯時依賴語言區域設置。語言區域設置只在匹配的時候影響其結果。
`re.``M``re.``MULTILINE`設置以后,樣式字符 `'^'` 匹配字符串的開始,和每一行的開始(換行符后面緊跟的符號);樣式字符 `'$'` 匹配字符串尾,和每一行的結尾(換行符前面那個符號)。默認情況下,`’^’` 匹配字符串頭,`'$'` 匹配字符串尾。對應內聯標記 `(?m)` 。
`re.``S``re.``DOTALL`讓 `'.'` 特殊字符匹配任何字符,包括換行符;如果沒有這個標記,`'.'` 就匹配 *除了* 換行符的其他任意字符。對應內聯標記 `(?s)` 。
`re.``X``re.``VERBOSE`這個標記允許你編寫更具可讀性更友好的正則表達式。通過分段和添加注釋。空白符號會被忽略,除非在一個字符集合當中或者由反斜杠轉義,或者在 `*?`, `(?:` or `(?P<…>` 分組之內。當一個行內有 `#` 不在字符集和轉義序列,那么它之后的所有字符都是注釋。
意思就是下面兩個正則表達式等價地匹配一個十進制數字:
```
a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
```
對應內聯標記 `(?x)` 。
`re.``search`(*pattern*, *string*, *flags=0*)掃描整個 *字符串* 找到匹配樣式的第一個位置,并返回一個相應的 [匹配對象](#match-objects)。如果沒有匹配,就返回一個 `None` ; 注意這和找到一個零長度匹配是不同的。
`re.``match`(*pattern*, *string*, *flags=0*)如果 *string* 開始的0或者多個字符匹配到了正則表達式樣式,就返回一個相應的 [匹配對象](#match-objects) 。 如果沒有匹配,就返回 `None` ;注意它跟零長度匹配是不同的。
注意即便是 [`MULTILINE`](#re.MULTILINE "re.MULTILINE") 多行模式, [`re.match()`](#re.match "re.match") 也只匹配字符串的開始位置,而不匹配每行開始。
如果你想定位 *string* 的任何位置,使用 [`search()`](#re.search "re.search") 來替代(也可參考 [search() vs. match()](#search-vs-match) )
`re.``fullmatch`(*pattern*, *string*, *flags=0*)如果整個 *string* 匹配到正則表達式樣式,就返回一個相應的 [匹配對象](#match-objects) 。 否則就返回一個 `None` ;注意這跟零長度匹配是不同的。
3\.4 新版功能.
`re.``split`(*pattern*, *string*, *maxsplit=0*, *flags=0*)用 *pattern* 分開 *string* 。 如果在 *pattern* 中捕獲到括號,那么所有的組里的文字也會包含在列表里。如果 *maxsplit* 非零, 最多進行 *maxsplit* 次分隔, 剩下的字符全部返回到列表的最后一個元素。
```
>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']
```
如果分隔符里有捕獲組合,并且匹配到字符串的開始,那么結果將會以一個空字符串開始。對于結尾也是一樣
```
>>> re.split(r'(\W+)', '...words, words...')
['', '...', 'words', ', ', 'words', '...', '']
```
這樣的話,分隔組將會出現在結果列表中同樣的位置。
樣式的空匹配將分開字符串,但只在不相臨的狀況生效。
```
>>> re.split(r'\b', 'Words, words, words.')
['', 'Words', ', ', 'words', ', ', 'words', '.']
>>> re.split(r'\W*', '...words...')
['', '', 'w', 'o', 'r', 'd', 's', '', '']
>>> re.split(r'(\W*)', '...words...')
['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']
```
在 3.1 版更改: 增加了可選標記參數。
在 3.7 版更改: 增加了空字符串的樣式分隔。
`re.``findall`(*pattern*, *string*, *flags=0*)對 *string* 返回一個不重復的 *pattern* 的匹配列表, *string* 從左到右進行掃描,匹配按找到的順序返回。如果樣式里存在一到多個組,就返回一個組合列表;就是一個元組的列表(如果樣式里有超過一個組合的話)。空匹配也會包含在結果里。
在 3.7 版更改: 非空匹配現在可以在前一個空匹配之后出現了。
`re.``finditer`(*pattern*, *string*, *flags=0*)*pattern* 在 *string* 里所有的非重復匹配,返回為一個迭代器 [iterator](../glossary.xhtml#term-iterator) 保存了 [匹配對象](#match-objects) 。 *string* 從左到右掃描,匹配按順序排列。空匹配也包含在結果里。
在 3.7 版更改: 非空匹配現在可以在前一個空匹配之后出現了。
`re.``sub`(*pattern*, *repl*, *string*, *count=0*, *flags=0*)返回通過使用 *repl* 替換在 *string* 最左邊非重疊出現的 *pattern* 而獲得的字符串。 如果樣式沒有找到,則不加改變地返回 *string*。 *repl* 可以是字符串或函數;如為字符串,則其中任何反斜杠轉義序列都會被處理。 也就是說,`\n` 會被轉換為一個換行符,`\r` 會被轉換為一個回車附,依此類推。 未知的 ASCII 字符轉義序列保留在未來使用,會被當作錯誤來處理。 其他未知轉義序列例如 `\&` 會保持原樣。 向后引用像是 `\6` 會用樣式中第 6 組所匹配到的子字符串來替換。 例如:
```
>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
... r'static PyObject*\npy_\1(void)\n{',
... 'def myfunc():')
'static PyObject*\npy_myfunc(void)\n{'
```
如果 *repl* 是一個函數,那它會對每個非重復的 *pattern* 的情況調用。這個函數只能有一個 [匹配對象](#match-objects) 參數,并返回一個替換后的字符串。比如
```
>>> def dashrepl(matchobj):
... if matchobj.group(0) == '-': return ' '
... else: return '-'
>>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
'pro--gram files'
>>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
'Baked Beans & Spam'
```
樣式可以是一個字符串或者一個 [樣式對象](#re-objects) 。
可選參數 *count* 是要替換的最大次數;*count* 必須是非負整數。如果忽略這個參數,或者設置為0,所有的匹配都會被替換。空匹配只在不相臨連續的情況被更替,所以 `sub('x*', '-', 'abxd')` 返回 `'-a-b--d-'` 。
在字符串類型的 *repl* 參數里,如上所述的轉義和向后引用中,`\g<name>` 會使用命名組合 `name`,(在 `(?P<name>…)` 語法中定義) `\g<number>` 會使用數字組;`\g<2>` 就是 `\2`,但它避免了二義性,如 `\g<2>0`。 `\20` 就會被解釋為組20,而不是組2后面跟隨一個字符 `'0'`。向后引用 `\g<0>` 把 *pattern* 作為一整個組進行引用。
在 3.1 版更改: 增加了可選標記參數。
在 3.5 版更改: 不匹配的組合替換為空字符串。
在 3.6 版更改: *pattern* 中的未知轉義(由 `'\'` 和一個 ASCII 字符組成)被視為錯誤。
在 3.7 版更改: *repl* 中的未知轉義(由 `'\'` 和一個 ASCII 字符組成)被視為錯誤。
在 3.7 版更改: 樣式中的空匹配相鄰接時會被替換。
`re.``subn`(*pattern*, *repl*, *string*, *count=0*, *flags=0*)行為與 [`sub()`](#re.sub "re.sub") 相同,但是返回一個元組 `(字符串, 替換次數)`.
在 3.1 版更改: 增加了可選標記參數。
在 3.5 版更改: 不匹配的組合替換為空字符串。
`re.``escape`(*pattern*)轉義 *pattern* 中的特殊字符。如果你想對任意可能包含正則表達式元字符的文本字符串進行匹配,它就是有用的。比如
```
>>> print(re.escape('python.exe'))
python\.exe
>>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:"
>>> print('[%s]+' % re.escape(legal_chars))
[abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&'\*\+\-\.\^_`\|\~:]+
>>> operators = ['+', '-', '*', '/', '**']
>>> print('|'.join(map(re.escape, sorted(operators, reverse=True))))
/|\-|\+|\*\*|\*
```
這個函數不能用在 [`sub()`](#re.sub "re.sub") 和 [`subn()`](#re.subn "re.subn") 的替換字符串里,只有反斜杠應該被轉義,比如說
```
>>> digits_re = r'\d+'
>>> sample = '/usr/sbin/sendmail - 0 errors, 12 warnings'
>>> print(re.sub(digits_re, digits_re.replace('\\', r'\\'), sample))
/usr/sbin/sendmail - \d+ errors, \d+ warnings
```
在 3.3 版更改: `'_'` 不再被轉義。
在 3.7 版更改: 只有在正則表達式中可以產生特殊含義的字符會被轉義。
`re.``purge`()清除正則表達式緩存。
*exception* `re.``error`(*msg*, *pattern=None*, *pos=None*)`raise` 一個例外。當傳遞到函數的字符串不是一個有效正則表達式的時候(比如,包含一個不匹配的括號)或者其他錯誤在編譯時或匹配時產生。如果字符串不包含樣式匹配,是不會被視為錯誤的。錯誤實例有以下附加屬性:
`msg`未格式化的錯誤消息。
`pattern`正則表達式樣式。
`pos`編譯失敗的 *pattern* 的位置索引(可以是 `None` )。
`lineno`對應 *pos* (可以是 `None`) 的行號。
`colno`對應 *pos* (可以是 `None`) 的列號。
在 3.5 版更改: 添加了附加屬性。
## 正則表達式對象 (正則對象)
編譯后的正則表達式對象支持一下方法和屬性:
`Pattern.``search`(*string*\[, *pos*\[, *endpos*\]\])掃描整個 *string* 尋找第一個匹配的位置, 并返回一個相應的 [匹配對象](#match-objects)。如果沒有匹配,就返回 `None` ;注意它和零長度匹配是不同的。
可選的第二個參數 *pos* 給出了字符串中開始搜索的位置索引;默認為 `0`,它不完全等價于字符串切片; `'^'` 樣式字符匹配字符串真正的開頭,和換行符后面的第一個字符,但不會匹配索引規定開始的位置。
可選參數 *endpos* 限定了字符串搜索的結束;它假定字符串長度到 *endpos* , 所以只有從 `pos` 到 `endpos - 1` 的字符會被匹配。如果 *endpos* 小于 *pos*,就不會有匹配產生;另外,如果 *rx* 是一個編譯后的正則對象, `rx.search(string, 0, 50)` 等價于 `rx.search(string[:50], 0)`。
```
>>> pattern = re.compile("d")
>>> pattern.search("dog") # Match at index 0
<re.Match object; span=(0, 1), match='d'>
>>> pattern.search("dog", 1) # No match; search doesn't include the "d"
```
`Pattern.``match`(*string*\[, *pos*\[, *endpos*\]\])如果 *string* 的 *開始位置* 能夠找到這個正則樣式的任意個匹配,就返回一個相應的 [匹配對象](#match-objects)。如果不匹配,就返回 `None` ;注意它與零長度匹配是不同的。
可選參數 *pos* 和 *endpos* 與 [`search()`](#re.Pattern.search "re.Pattern.search") 含義相同。
```
>>> pattern = re.compile("o")
>>> pattern.match("dog") # No match as "o" is not at the start of "dog".
>>> pattern.match("dog", 1) # Match as "o" is the 2nd character of "dog".
<re.Match object; span=(1, 2), match='o'>
```
如果你想定位匹配在 *string* 中的位置,使用 [`search()`](#re.Pattern.search "re.Pattern.search") 來替代(另參考 [search() vs. match()](#search-vs-match))。
`Pattern.``fullmatch`(*string*\[, *pos*\[, *endpos*\]\])如果整個 *string* 匹配這個正則表達式,就返回一個相應的 [匹配對象](#match-objects) 。 否則就返回 `None` ; 注意跟零長度匹配是不同的。
可選參數 *pos* 和 *endpos* 與 [`search()`](#re.Pattern.search "re.Pattern.search") 含義相同。
```
>>> pattern = re.compile("o[gh]")
>>> pattern.fullmatch("dog") # No match as "o" is not at the start of "dog".
>>> pattern.fullmatch("ogre") # No match as not the full string matches.
>>> pattern.fullmatch("doggie", 1, 3) # Matches within given limits.
<re.Match object; span=(1, 3), match='og'>
```
3\.4 新版功能.
`Pattern.``split`(*string*, *maxsplit=0*)等價于 [`split()`](#re.split "re.split") 函數,使用了編譯后的樣式。
`Pattern.``findall`(*string*\[, *pos*\[, *endpos*\]\])類似函數 [`findall()`](#re.findall "re.findall") , 使用了編譯后樣式,但也可以接收可選參數 *pos* 和 *endpos* ,限制搜索范圍,就像 [`search()`](#re.search "re.search")。
`Pattern.``finditer`(*string*\[, *pos*\[, *endpos*\]\])類似函數 `finiter()` , 使用了編譯后樣式,但也可以接收可選參數 *pos* 和 *endpos* ,限制搜索范圍,就像 [`search()`](#re.search "re.search")。
`Pattern.``sub`(*repl*, *string*, *count=0*)等價于 [`sub()`](#re.sub "re.sub") 函數,使用了編譯后的樣式。
`Pattern.``subn`(*repl*, *string*, *count=0*)等價于 [`subn()`](#re.subn "re.subn") 函數,使用了編譯后的樣式。
`Pattern.``flags`正則匹配標記。這是可以傳遞給 [`compile()`](#re.compile "re.compile") 的參數,任何 `(?…)` 內聯標記,隱性標記比如 `UNICODE` 的結合。
`Pattern.``groups`捕獲組合的數量。
`Pattern.``groupindex`映射由 `(?P<id>)` 定義的命名符號組合和數字組合的字典。如果沒有符號組,那字典就是空的。
`Pattern.``pattern`編譯對象的原始樣式字符串。
在 3.7 版更改: 添加 [`copy.copy()`](copy.xhtml#copy.copy "copy.copy") 和 [`copy.deepcopy()`](copy.xhtml#copy.deepcopy "copy.deepcopy") 函數的支持。編譯后的正則表達式對象被認為是原子性的。
## 匹配對象
匹配對象總是有一個布爾值 `True`。如果沒有匹配的話 [`match()`](#re.Pattern.match "re.Pattern.match") 和 [`search()`](#re.Pattern.search "re.Pattern.search") 返回 `None` 所以你可以簡單的用 `if` 語句來判斷是否匹配
```
match = re.search(pattern, string)
if match:
process(match)
```
匹配對象支持以下方法和屬性:
`Match.``expand`(*template*)對 *template* 進行反斜杠轉義替換并且返回,就像 [`sub()`](#re.Pattern.sub "re.Pattern.sub") 方法中一樣。轉義如同 `\n` 被轉換成合適的字符,數字引用(`\1`, `\2`)和命名組合(`\g<1>`, `\g<name>`) 替換為相應組合的內容。
在 3.5 版更改: 不匹配的組合替換為空字符串。
`Match.``group`(\[*group1*, *...*\])返回一個或者多個匹配的子組。如果只有一個參數,結果就是一個字符串,如果有多個參數,結果就是一個元組(每個參數對應一個項),如果沒有參數,組1默認到0(整個匹配都被返回)。 如果一個組N 參數值為 0,相應的返回值就是整個匹配字符串;如果它是一個范圍 \[1..99\],結果就是相應的括號組字符串。如果一個組號是負數,或者大于樣式中定義的組數,一個 [`IndexError`](exceptions.xhtml#IndexError "IndexError") 索引錯誤就 `raise`。如果一個組包含在樣式的一部分,并被匹配多次,就返回最后一個匹配。:
```
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0) # The entire match
'Isaac Newton'
>>> m.group(1) # The first parenthesized subgroup.
'Isaac'
>>> m.group(2) # The second parenthesized subgroup.
'Newton'
>>> m.group(1, 2) # Multiple arguments give us a tuple.
('Isaac', 'Newton')
```
如果正則表達式使用了 `(?P<name>…)` 語法, *groupN* 參數就也可能是命名組合的名字。如果一個字符串參數在樣式中未定義為組合名,一個 [`IndexError`](exceptions.xhtml#IndexError "IndexError") 就 `raise`。
一個相對復雜的例子
```
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.group('first_name')
'Malcolm'
>>> m.group('last_name')
'Reynolds'
```
命名組合同樣可以通過索引值引用
```
>>> m.group(1)
'Malcolm'
>>> m.group(2)
'Reynolds'
```
如果一個組匹配成功多次,就只返回最后一個匹配
```
>>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times.
>>> m.group(1) # Returns only the last match.
'c3'
```
`Match.``__getitem__`(*g*)這個等價于 `m.group(g)`。這允許更方便的引用一個匹配
```
>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m[0] # The entire match
'Isaac Newton'
>>> m[1] # The first parenthesized subgroup.
'Isaac'
>>> m[2] # The second parenthesized subgroup.
'Newton'
```
3\.6 新版功能.
`Match.``groups`(*default=None*)返回一個元組,包含所有匹配的子組,在樣式中出現的從1到任意多的組合。 *default* 參數用于不參與匹配的情況,默認為 `None`。
例如
```
>>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
>>> m.groups()
('24', '1632')
```
如果我們使小數點可選,那么不是所有的組都會參與到匹配當中。這些組合默認會返回一個 `None` ,除非指定了 *default* 參數。
```
>>> m = re.match(r"(\d+)\.?(\d+)?", "24")
>>> m.groups() # Second group defaults to None.
('24', None)
>>> m.groups('0') # Now, the second group defaults to '0'.
('24', '0')
```
`Match.``groupdict`(*default=None*)返回一個字典,包含了所有的 *命名* 子組。key就是組名。 *default* 參數用于不參與匹配的組合;默認為 `None`。 例如
```
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.groupdict()
{'first_name': 'Malcolm', 'last_name': 'Reynolds'}
```
`Match.``start`(\[*group*\])`Match.``end`(\[*group*\])返回 *group* 匹配到的字串的開始和結束標號。*group* 默認為0(意思是整個匹配的子串)。如果 *group* 存在,但未產生匹配,就返回 `-1` 。對于一個匹配對象 *m*, 和一個未參與匹配的組 *g* ,組 *g* (等價于 `m.group(g)`)產生的匹配是
```
m.string[m.start(g):m.end(g)]
```
注意 `m.start(group)` 將會等于 `m.end(group)` ,如果 *group* 匹配一個空字符串的話。比如,在 `m = re.search('b(c?)', 'cba')` 之后,`m.start(0)` 為 1, `m.end(0)` 為 2, `m.start(1)` 和 `m.end(1)` 都是 2, `m.start(2)` raise 一個 [`IndexError`](exceptions.xhtml#IndexError "IndexError") 例外。
這個例子會從email地址中移除掉 *remove\_this*
```
>>> email = "tony@tiremove_thisger.net"
>>> m = re.search("remove_this", email)
>>> email[:m.start()] + email[m.end():]
'tony@tiger.net'
```
`Match.``span`(\[*group*\])對于一個匹配 *m* , 返回一個二元組 `(m.start(group), m.end(group))` 。 注意如果 *group* 沒有在這個匹配中,就返回 `(-1, -1)` 。*group* 默認為0,就是整個匹配。
`Match.``pos`*pos* 的值,會傳遞給 [`search()`](#re.Pattern.search "re.Pattern.search") 或 [`match()`](#re.Pattern.match "re.Pattern.match") 的方法 a [正則對象](#re-objects) 。這個是正則引擎開始在字符串搜索一個匹配的索引位置。
`Match.``endpos`*endpos* 的值,會傳遞給 [`search()`](#re.Pattern.search "re.Pattern.search") 或 [`match()`](#re.Pattern.match "re.Pattern.match") 的方法 a [正則對象](#re-objects) 。這個是正則引擎停止在字符串搜索一個匹配的索引位置。
`Match.``lastindex`捕獲組的最后一個匹配的整數索引值,或者 `None` 如果沒有匹配產生的話。比如,對于字符串 `'ab'`,表達式 `(a)b`, `((a)(b))`, 和 `((ab))` 將得到 `lastindex == 1` , 而 `(a)(b)` 會得到 `lastindex == 2` 。
`Match.``lastgroup`最后一個匹配的命名組名字,或者 `None` 如果沒有產生匹配的話。
`Match.``re`返回產生這個實例的 [正則對象](#re-objects) , 這個實例是由 正則對象的 [`match()`](#re.Pattern.match "re.Pattern.match") 或 [`search()`](#re.Pattern.search "re.Pattern.search") 方法產生的。
`Match.``string`傳遞到 [`match()`](#re.Pattern.match "re.Pattern.match") 或 [`search()`](#re.Pattern.search "re.Pattern.search") 的字符串。
在 3.7 版更改: 添加了對 [`copy.copy()`](copy.xhtml#copy.copy "copy.copy") 和 [`copy.deepcopy()`](copy.xhtml#copy.deepcopy "copy.deepcopy") 的支持。匹配對象被看作是原子性的。
## 正則表達式例子
### 檢查對子
在這個例子里,我們使用以下輔助函數來更好的顯示匹配對象:
```
def displaymatch(match):
if match is None:
return None
return '<Match: %r, groups=%r>' % (match.group(), match.groups())
```
假設你在寫一個撲克程序,一個玩家的一手牌為五個字符的串,每個字符表示一張牌,"a" 就是 A, "k" K, "q" Q, "j" J, "t" 為 10, "2" 到 "9" 表示2 到 9。
要看給定的字符串是否有效,我們可以按照以下步驟
```
>>> valid = re.compile(r"^[a2-9tjqk]{5}$")
>>> displaymatch(valid.match("akt5q")) # Valid.
"<Match: 'akt5q', groups=()>"
>>> displaymatch(valid.match("akt5e")) # Invalid.
>>> displaymatch(valid.match("akt")) # Invalid.
>>> displaymatch(valid.match("727ak")) # Valid.
"<Match: '727ak', groups=()>"
```
最后一手牌,`"727ak"` ,包含了一個對子,或者兩張同樣數值的牌。要用正則表達式匹配它,應該使用向后引用如下
```
>>> pair = re.compile(r".*(.).*\1")
>>> displaymatch(pair.match("717ak")) # Pair of 7s.
"<Match: '717', groups=('7',)>"
>>> displaymatch(pair.match("718ak")) # No pairs.
>>> displaymatch(pair.match("354aa")) # Pair of aces.
"<Match: '354aa', groups=('a',)>"
```
要找到對子包含的是哪一張牌,應該按照下面的方式使用 [`group()`](#re.Match.group "re.Match.group") 方法:
```
>>> pair.match("717ak").group(1)
'7'
# Error because re.match() returns None, which doesn't have a group() method:
>>> pair.match("718ak").group(1)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
re.match(r".*(.).*\1", "718ak").group(1)
AttributeError: 'NoneType' object has no attribute 'group'
>>> pair.match("354aa").group(1)
'a'
```
### 模擬 scanf()
Python 目前沒有一個類似c函數 `scanf()` 的替代品。正則表達式通常比 `scanf()` 格式字符串要更強大一些,但也帶來更多復雜性。下面的表格提供了 `scanf()` 格式符和正則表達式大致相同的映射。
`scanf()` 格式符
正則表達式
`%c`
`.`
`%5c`
`.{5}`
`%d`
`[-+]?\d+`
`%e`, `%E`, `%f`, `%g`
`[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?`
`%i`
`[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)`
`%o`
`[-+]?[0-7]+`
`%s`
`\S+`
`%u`
`\d+`
`%x`, `%X`
`[-+]?(0[xX])?[\dA-Fa-f]+`
從文件名和數字提取字符串
```
/usr/sbin/sendmail - 0 errors, 4 warnings
```
你可以使用 `scanf()` 格式化
```
%s - %d errors, %d warnings
```
等價的正則表達式是:
```
(\S+) - (\d+) errors, (\d+) warnings
```
### search() vs. match()
Python 提供了兩種不同的操作:基于 [`re.match()`](#re.match "re.match") 檢查字符串開頭,或者 [`re.search()`](#re.search "re.search") 檢查字符串的任意位置(默認Perl中的行為)。
例如
```
>>> re.match("c", "abcdef") # No match
>>> re.search("c", "abcdef") # Match
<re.Match object; span=(2, 3), match='c'>
```
在 [`search()`](#re.search "re.search") 中,可以用 `'^'` 作為開始來限制匹配到字符串的首位
```
>>> re.match("c", "abcdef") # No match
>>> re.search("^c", "abcdef") # No match
>>> re.search("^a", "abcdef") # Match
<re.Match object; span=(0, 1), match='a'>
```
注意 [`MULTILINE`](#re.MULTILINE "re.MULTILINE") 多行模式中函數 [`match()`](#re.match "re.match") 只匹配字符串的開始,但使用 [`search()`](#re.search "re.search") 和以 `'^'` 開始的正則表達式會匹配每行的開始
```
>>> re.match('X', 'A\nB\nX', re.MULTILINE) # No match
>>> re.search('^X', 'A\nB\nX', re.MULTILINE) # Match
<re.Match object; span=(4, 5), match='X'>
```
### 建立一個電話本
[`split()`](#re.split "re.split") 將字符串用參數傳遞的樣式分隔開。這個方法對于轉換文本數據到易讀而且容易修改的數據結構,是很有用的,如下面的例子證明。
首先,這里是輸入。通常是一個文件,這里我們用三引號字符串語法
```
>>> text = """Ross McFluff: 834.345.1254 155 Elm Street
...
... Ronald Heathmore: 892.345.3428 436 Finley Avenue
... Frank Burger: 925.541.7625 662 South Dogwood Way
...
...
... Heather Albrecht: 548.326.4584 919 Park Place"""
```
條目用一個或者多個換行符分開。現在我們將字符串轉換為一個列表,每個非空行都有一個條目:
```
>>> entries = re.split("\n+", text)
>>> entries
['Ross McFluff: 834.345.1254 155 Elm Street',
'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
'Frank Burger: 925.541.7625 662 South Dogwood Way',
'Heather Albrecht: 548.326.4584 919 Park Place']
```
最終,將每個條目分割為一個由名字、姓氏、電話號碼和地址組成的列表。我們為 [`split()`](#re.split "re.split") 使用了 `maxsplit` 形參,因為地址中包含有被我們作為分割模式的空格符:
```
>>> [re.split(":? ", entry, 3) for entry in entries]
[['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]
```
`:?` 樣式匹配姓后面的冒號,因此它不出現在結果列表中。如果 `maxsplit` 設置為 `4` ,我們還可以從地址中獲取到房間號:
```
>>> [re.split(":? ", entry, 4) for entry in entries]
[['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]
```
### 文字整理
[`sub()`](#re.sub "re.sub") 替換字符串中出現的樣式的每一個實例。這個例子證明了使用 [`sub()`](#re.sub "re.sub") 來整理文字,或者隨機化每個字符的位置,除了首位和末尾字符
```
>>> def repl(m):
... inner_word = list(m.group(2))
... random.shuffle(inner_word)
... return m.group(1) + "".join(inner_word) + m.group(3)
>>> text = "Professor Abdolmalek, please report your absences promptly."
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
>>> re.sub(r"(\w)(\w+)(\w)", repl, text)
'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
```
### 找到所有副詞
[`findall()`](#re.findall "re.findall") 匹配樣式 *所有* 的出現,不僅是像 [`search()`](#re.search "re.search") 中的第一個匹配。比如,如果一個作者希望找到文字中的所有副詞,他可能會按照以下方法用 [`findall()`](#re.findall "re.findall")
```
>>> text = "He was carefully disguised but captured quickly by police."
>>> re.findall(r"\w+ly", text)
['carefully', 'quickly']
```
### 找到所有副詞和位置
如果需要匹配樣式的更多信息, [`finditer()`](#re.finditer "re.finditer") 可以起到作用,它提供了 [匹配對象](#match-objects) 作為返回值,而不是字符串。繼續上面的例子,如果一個作者希望找到所有副詞和它的位置,可以按照下面方法使用 [`finditer()`](#re.finditer "re.finditer")
```
>>> text = "He was carefully disguised but captured quickly by police."
>>> for m in re.finditer(r"\w+ly", text):
... print('%02d-%02d: %s' % (m.start(), m.end(), m.group(0)))
07-16: carefully
40-47: quickly
```
### 原始字符記法
原始字符串記法 (`r"text"`) 保持正則表達式正常。否則,每個正則式里的反斜杠(`'\'`) 都必須前綴一個反斜杠來轉義。比如,下面兩行代碼功能就是完全一致的
```
>>> re.match(r"\W(.)\1\W", " ff ")
<re.Match object; span=(0, 4), match=' ff '>
>>> re.match("\\W(.)\\1\\W", " ff ")
<re.Match object; span=(0, 4), match=' ff '>
```
當需要匹配一個字符反斜杠,它必須在正則表達式中轉義。在原始字符串記法,就是 `r"\\"`。否則就必須用 `"\\\\"`,來表示同樣的意思
```
>>> re.match(r"\\", r"\\")
<re.Match object; span=(0, 1), match='\\'>
>>> re.match("\\\\", r"\\")
<re.Match object; span=(0, 1), match='\\'>
```
### 寫一個詞法分析器
一個 [詞法器或詞法分析器](https://en.wikipedia.org/wiki/Lexical_analysis) \[https://en.wikipedia.org/wiki/Lexical\_analysis\] 分析字符串,并分類成目錄組。 這是寫一個編譯器或解釋器的第一步。
文字目錄是由正則表達式指定的。這個技術是通過將這些樣式合并為一個主正則式,并且循環匹配來實現的
```
import collections
import re
Token = collections.namedtuple('Token', ['type', 'value', 'line', 'column'])
def tokenize(code):
keywords = {'IF', 'THEN', 'ENDIF', 'FOR', 'NEXT', 'GOSUB', 'RETURN'}
token_specification = [
('NUMBER', r'\d+(\.\d*)?'), # Integer or decimal number
('ASSIGN', r':='), # Assignment operator
('END', r';'), # Statement terminator
('ID', r'[A-Za-z]+'), # Identifiers
('OP', r'[+\-*/]'), # Arithmetic operators
('NEWLINE', r'\n'), # Line endings
('SKIP', r'[ \t]+'), # Skip over spaces and tabs
('MISMATCH', r'.'), # Any other character
]
tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
line_num = 1
line_start = 0
for mo in re.finditer(tok_regex, code):
kind = mo.lastgroup
value = mo.group()
column = mo.start() - line_start
if kind == 'NUMBER':
value = float(value) if '.' in value else int(value)
elif kind == 'ID' and value in keywords:
kind = value
elif kind == 'NEWLINE':
line_start = mo.end()
line_num += 1
continue
elif kind == 'SKIP':
continue
elif kind == 'MISMATCH':
raise RuntimeError(f'{value!r} unexpected on line {line_num}')
yield Token(kind, value, line_num, column)
statements = '''
IF quantity THEN
total := total + price * quantity;
tax := price * 0.05;
ENDIF;
'''
for token in tokenize(statements):
print(token)
```
這個詞法器產生以下輸出
```
Token(type='IF', value='IF', line=2, column=4)
Token(type='ID', value='quantity', line=2, column=7)
Token(type='THEN', value='THEN', line=2, column=16)
Token(type='ID', value='total', line=3, column=8)
Token(type='ASSIGN', value=':=', line=3, column=14)
Token(type='ID', value='total', line=3, column=17)
Token(type='OP', value='+', line=3, column=23)
Token(type='ID', value='price', line=3, column=25)
Token(type='OP', value='*', line=3, column=31)
Token(type='ID', value='quantity', line=3, column=33)
Token(type='END', value=';', line=3, column=41)
Token(type='ID', value='tax', line=4, column=8)
Token(type='ASSIGN', value=':=', line=4, column=12)
Token(type='ID', value='price', line=4, column=15)
Token(type='OP', value='*', line=4, column=21)
Token(type='NUMBER', value=0.05, line=4, column=23)
Token(type='END', value=';', line=4, column=27)
Token(type='ENDIF', value='ENDIF', line=5, column=4)
Token(type='END', value=';', line=5, column=9)
```
[Frie09](#id1)Friedl, Jeffrey. Mastering Regular Expressions. 第三版, O’Reilly Media, 2009. 第三版不再使用Python, 但第一版提供了編寫正則表達式的良好細節。
### 導航
- [索引](../genindex.xhtml "總目錄")
- [模塊](../py-modindex.xhtml "Python 模塊索引") |
- [下一頁](difflib.xhtml "模塊 difflib 是一個計算差異的助手") |
- [上一頁](string.xhtml "string --- 常見的字符串操作") |
- 
- [Python](https://www.python.org/) ?
- zh\_CN 3.7.3 [文檔](../index.xhtml) ?
- [Python 標準庫](index.xhtml) ?
- [文本處理服務](text.xhtml) ?
- $('.inline-search').show(0); |
? [版權所有](../copyright.xhtml) 2001-2019, Python Software Foundation.
Python 軟件基金會是一個非盈利組織。 [請捐助。](https://www.python.org/psf/donations/)
最后更新于 5月 21, 2019. [發現了問題](../bugs.xhtml)?
使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 創建。
- Python文檔內容
- Python 有什么新變化?
- Python 3.7 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- C API 的改變
- 構建的改變
- 性能優化
- 其他 CPython 實現的改變
- 已棄用的 Python 行為
- 已棄用的 Python 模塊、函數和方法
- 已棄用的 C API 函數和類型
- 平臺支持的移除
- API 與特性的移除
- 移除的模塊
- Windows 專屬的改變
- 移植到 Python 3.7
- Python 3.7.1 中的重要變化
- Python 3.7.2 中的重要變化
- Python 3.6 有什么新變化A
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 其他改進
- 棄用
- 移除
- 移植到Python 3.6
- Python 3.6.2 中的重要變化
- Python 3.6.4 中的重要變化
- Python 3.6.5 中的重要變化
- Python 3.6.7 中的重要變化
- Python 3.5 有什么新變化
- 摘要 - 發布重點
- 新的特性
- 其他語言特性修改
- 新增模塊
- 改進的模塊
- Other module-level changes
- 性能優化
- Build and C API Changes
- 棄用
- 移除
- Porting to Python 3.5
- Notable changes in Python 3.5.4
- What's New In Python 3.4
- 摘要 - 發布重點
- 新的特性
- 新增模塊
- 改進的模塊
- CPython Implementation Changes
- 棄用
- 移除
- Porting to Python 3.4
- Changed in 3.4.3
- What's New In Python 3.3
- 摘要 - 發布重點
- PEP 405: Virtual Environments
- PEP 420: Implicit Namespace Packages
- PEP 3118: New memoryview implementation and buffer protocol documentation
- PEP 393: Flexible String Representation
- PEP 397: Python Launcher for Windows
- PEP 3151: Reworking the OS and IO exception hierarchy
- PEP 380: Syntax for Delegating to a Subgenerator
- PEP 409: Suppressing exception context
- PEP 414: Explicit Unicode literals
- PEP 3155: Qualified name for classes and functions
- PEP 412: Key-Sharing Dictionary
- PEP 362: Function Signature Object
- PEP 421: Adding sys.implementation
- Using importlib as the Implementation of Import
- 其他語言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模塊
- 改進的模塊
- 性能優化
- Build and C API Changes
- 棄用
- Porting to Python 3.3
- What's New In Python 3.2
- PEP 384: Defining a Stable ABI
- PEP 389: Argparse Command Line Parsing Module
- PEP 391: Dictionary Based Configuration for Logging
- PEP 3148: The concurrent.futures module
- PEP 3147: PYC Repository Directories
- PEP 3149: ABI Version Tagged .so Files
- PEP 3333: Python Web Server Gateway Interface v1.0.1
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 多線程
- 性能優化
- Unicode
- Codecs
- 文檔
- IDLE
- Code Repository
- Build and C API Changes
- Porting to Python 3.2
- What's New In Python 3.1
- PEP 372: Ordered Dictionaries
- PEP 378: Format Specifier for Thousands Separator
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- 性能優化
- IDLE
- Build and C API Changes
- Porting to Python 3.1
- What's New In Python 3.0
- Common Stumbling Blocks
- Overview Of Syntax Changes
- Changes Already Present In Python 2.6
- Library Changes
- PEP 3101: A New Approach To String Formatting
- Changes To Exceptions
- Miscellaneous Other Changes
- Build and C API Changes
- 性能
- Porting To Python 3.0
- What's New in Python 2.7
- The Future for Python 2.x
- Changes to the Handling of Deprecation Warnings
- Python 3.1 Features
- PEP 372: Adding an Ordered Dictionary to collections
- PEP 378: Format Specifier for Thousands Separator
- PEP 389: The argparse Module for Parsing Command Lines
- PEP 391: Dictionary-Based Configuration For Logging
- PEP 3106: Dictionary Views
- PEP 3137: The memoryview Object
- 其他語言特性修改
- New and Improved Modules
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.7
- New Features Added to Python 2.7 Maintenance Releases
- Acknowledgements
- Python 2.6 有什么新變化
- Python 3.0
- Changes to the Development Process
- PEP 343: The 'with' statement
- PEP 366: Explicit Relative Imports From a Main Module
- PEP 370: Per-user site-packages Directory
- PEP 371: The multiprocessing Package
- PEP 3101: Advanced String Formatting
- PEP 3105: print As a Function
- PEP 3110: Exception-Handling Changes
- PEP 3112: Byte Literals
- PEP 3116: New I/O Library
- PEP 3118: Revised Buffer Protocol
- PEP 3119: Abstract Base Classes
- PEP 3127: Integer Literal Support and Syntax
- PEP 3129: Class Decorators
- PEP 3141: A Type Hierarchy for Numbers
- 其他語言特性修改
- New and Improved Modules
- Deprecations and Removals
- Build and C API Changes
- Porting to Python 2.6
- Acknowledgements
- What's New in Python 2.5
- PEP 308: Conditional Expressions
- PEP 309: Partial Function Application
- PEP 314: Metadata for Python Software Packages v1.1
- PEP 328: Absolute and Relative Imports
- PEP 338: Executing Modules as Scripts
- PEP 341: Unified try/except/finally
- PEP 342: New Generator Features
- PEP 343: The 'with' statement
- PEP 352: Exceptions as New-Style Classes
- PEP 353: Using ssize_t as the index type
- PEP 357: The 'index' method
- 其他語言特性修改
- New, Improved, and Removed Modules
- Build and C API Changes
- Porting to Python 2.5
- Acknowledgements
- What's New in Python 2.4
- PEP 218: Built-In Set Objects
- PEP 237: Unifying Long Integers and Integers
- PEP 289: Generator Expressions
- PEP 292: Simpler String Substitutions
- PEP 318: Decorators for Functions and Methods
- PEP 322: Reverse Iteration
- PEP 324: New subprocess Module
- PEP 327: Decimal Data Type
- PEP 328: Multi-line Imports
- PEP 331: Locale-Independent Float/String Conversions
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Build and C API Changes
- Porting to Python 2.4
- Acknowledgements
- What's New in Python 2.3
- PEP 218: A Standard Set Datatype
- PEP 255: Simple Generators
- PEP 263: Source Code Encodings
- PEP 273: Importing Modules from ZIP Archives
- PEP 277: Unicode file name support for Windows NT
- PEP 278: Universal Newline Support
- PEP 279: enumerate()
- PEP 282: The logging Package
- PEP 285: A Boolean Type
- PEP 293: Codec Error Handling Callbacks
- PEP 301: Package Index and Metadata for Distutils
- PEP 302: New Import Hooks
- PEP 305: Comma-separated Files
- PEP 307: Pickle Enhancements
- Extended Slices
- 其他語言特性修改
- New, Improved, and Deprecated Modules
- Pymalloc: A Specialized Object Allocator
- Build and C API Changes
- Other Changes and Fixes
- Porting to Python 2.3
- Acknowledgements
- What's New in Python 2.2
- 概述
- PEPs 252 and 253: Type and Class Changes
- PEP 234: Iterators
- PEP 255: Simple Generators
- PEP 237: Unifying Long Integers and Integers
- PEP 238: Changing the Division Operator
- Unicode Changes
- PEP 227: Nested Scopes
- New and Improved Modules
- Interpreter Changes and Fixes
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.1
- 概述
- PEP 227: Nested Scopes
- PEP 236: future Directives
- PEP 207: Rich Comparisons
- PEP 230: Warning Framework
- PEP 229: New Build System
- PEP 205: Weak References
- PEP 232: Function Attributes
- PEP 235: Importing Modules on Case-Insensitive Platforms
- PEP 217: Interactive Display Hook
- PEP 208: New Coercion Model
- PEP 241: Metadata in Python Packages
- New and Improved Modules
- Other Changes and Fixes
- Acknowledgements
- What's New in Python 2.0
- 概述
- What About Python 1.6?
- New Development Process
- Unicode
- 列表推導式
- Augmented Assignment
- 字符串的方法
- Garbage Collection of Cycles
- Other Core Changes
- Porting to 2.0
- Extending/Embedding Changes
- Distutils: Making Modules Easy to Install
- XML Modules
- Module changes
- New modules
- IDLE Improvements
- Deleted and Deprecated Modules
- Acknowledgements
- 更新日志
- Python 下一版
- Python 3.7.3 最終版
- Python 3.7.3 發布候選版 1
- Python 3.7.2 最終版
- Python 3.7.2 發布候選版 1
- Python 3.7.1 最終版
- Python 3.7.1 RC 2版本
- Python 3.7.1 發布候選版 1
- Python 3.7.0 正式版
- Python 3.7.0 release candidate 1
- Python 3.7.0 beta 5
- Python 3.7.0 beta 4
- Python 3.7.0 beta 3
- Python 3.7.0 beta 2
- Python 3.7.0 beta 1
- Python 3.7.0 alpha 4
- Python 3.7.0 alpha 3
- Python 3.7.0 alpha 2
- Python 3.7.0 alpha 1
- Python 3.6.6 final
- Python 3.6.6 RC 1
- Python 3.6.5 final
- Python 3.6.5 release candidate 1
- Python 3.6.4 final
- Python 3.6.4 release candidate 1
- Python 3.6.3 final
- Python 3.6.3 release candidate 1
- Python 3.6.2 final
- Python 3.6.2 release candidate 2
- Python 3.6.2 release candidate 1
- Python 3.6.1 final
- Python 3.6.1 release candidate 1
- Python 3.6.0 final
- Python 3.6.0 release candidate 2
- Python 3.6.0 release candidate 1
- Python 3.6.0 beta 4
- Python 3.6.0 beta 3
- Python 3.6.0 beta 2
- Python 3.6.0 beta 1
- Python 3.6.0 alpha 4
- Python 3.6.0 alpha 3
- Python 3.6.0 alpha 2
- Python 3.6.0 alpha 1
- Python 3.5.5 final
- Python 3.5.5 release candidate 1
- Python 3.5.4 final
- Python 3.5.4 release candidate 1
- Python 3.5.3 final
- Python 3.5.3 release candidate 1
- Python 3.5.2 final
- Python 3.5.2 release candidate 1
- Python 3.5.1 final
- Python 3.5.1 release candidate 1
- Python 3.5.0 final
- Python 3.5.0 release candidate 4
- Python 3.5.0 release candidate 3
- Python 3.5.0 release candidate 2
- Python 3.5.0 release candidate 1
- Python 3.5.0 beta 4
- Python 3.5.0 beta 3
- Python 3.5.0 beta 2
- Python 3.5.0 beta 1
- Python 3.5.0 alpha 4
- Python 3.5.0 alpha 3
- Python 3.5.0 alpha 2
- Python 3.5.0 alpha 1
- Python 教程
- 課前甜點
- 使用 Python 解釋器
- 調用解釋器
- 解釋器的運行環境
- Python 的非正式介紹
- Python 作為計算器使用
- 走向編程的第一步
- 其他流程控制工具
- if 語句
- for 語句
- range() 函數
- break 和 continue 語句,以及循環中的 else 子句
- pass 語句
- 定義函數
- 函數定義的更多形式
- 小插曲:編碼風格
- 數據結構
- 列表的更多特性
- del 語句
- 元組和序列
- 集合
- 字典
- 循環的技巧
- 深入條件控制
- 序列和其它類型的比較
- 模塊
- 有關模塊的更多信息
- 標準模塊
- dir() 函數
- 包
- 輸入輸出
- 更漂亮的輸出格式
- 讀寫文件
- 錯誤和異常
- 語法錯誤
- 異常
- 處理異常
- 拋出異常
- 用戶自定義異常
- 定義清理操作
- 預定義的清理操作
- 類
- 名稱和對象
- Python 作用域和命名空間
- 初探類
- 補充說明
- 繼承
- 私有變量
- 雜項說明
- 迭代器
- 生成器
- 生成器表達式
- 標準庫簡介
- 操作系統接口
- 文件通配符
- 命令行參數
- 錯誤輸出重定向和程序終止
- 字符串模式匹配
- 數學
- 互聯網訪問
- 日期和時間
- 數據壓縮
- 性能測量
- 質量控制
- 自帶電池
- 標準庫簡介 —— 第二部分
- 格式化輸出
- 模板
- 使用二進制數據記錄格式
- 多線程
- 日志
- 弱引用
- 用于操作列表的工具
- 十進制浮點運算
- 虛擬環境和包
- 概述
- 創建虛擬環境
- 使用pip管理包
- 接下來?
- 交互式編輯和編輯歷史
- Tab 補全和編輯歷史
- 默認交互式解釋器的替代品
- 浮點算術:爭議和限制
- 表示性錯誤
- 附錄
- 交互模式
- 安裝和使用 Python
- 命令行與環境
- 命令行
- 環境變量
- 在Unix平臺中使用Python
- 獲取最新版本的Python
- 構建Python
- 與Python相關的路徑和文件
- 雜項
- 編輯器和集成開發環境
- 在Windows上使用 Python
- 完整安裝程序
- Microsoft Store包
- nuget.org 安裝包
- 可嵌入的包
- 替代捆綁包
- 配置Python
- 適用于Windows的Python啟動器
- 查找模塊
- 附加模塊
- 在Windows上編譯Python
- 其他平臺
- 在蘋果系統上使用 Python
- 獲取和安裝 MacPython
- IDE
- 安裝額外的 Python 包
- Mac 上的圖形界面編程
- 在 Mac 上分發 Python 應用程序
- 其他資源
- Python 語言參考
- 概述
- 其他實現
- 標注
- 詞法分析
- 行結構
- 其他形符
- 標識符和關鍵字
- 字面值
- 運算符
- 分隔符
- 數據模型
- 對象、值與類型
- 標準類型層級結構
- 特殊方法名稱
- 協程
- 執行模型
- 程序的結構
- 命名與綁定
- 異常
- 導入系統
- importlib
- 包
- 搜索
- 加載
- 基于路徑的查找器
- 替換標準導入系統
- Package Relative Imports
- 有關 main 的特殊事項
- 開放問題項
- 參考文獻
- 表達式
- 算術轉換
- 原子
- 原型
- await 表達式
- 冪運算符
- 一元算術和位運算
- 二元算術運算符
- 移位運算
- 二元位運算
- 比較運算
- 布爾運算
- 條件表達式
- lambda 表達式
- 表達式列表
- 求值順序
- 運算符優先級
- 簡單語句
- 表達式語句
- 賦值語句
- assert 語句
- pass 語句
- del 語句
- return 語句
- yield 語句
- raise 語句
- break 語句
- continue 語句
- import 語句
- global 語句
- nonlocal 語句
- 復合語句
- if 語句
- while 語句
- for 語句
- try 語句
- with 語句
- 函數定義
- 類定義
- 協程
- 最高層級組件
- 完整的 Python 程序
- 文件輸入
- 交互式輸入
- 表達式輸入
- 完整的語法規范
- Python 標準庫
- 概述
- 可用性注釋
- 內置函數
- 內置常量
- 由 site 模塊添加的常量
- 內置類型
- 邏輯值檢測
- 布爾運算 — and, or, not
- 比較
- 數字類型 — int, float, complex
- 迭代器類型
- 序列類型 — list, tuple, range
- 文本序列類型 — str
- 二進制序列類型 — bytes, bytearray, memoryview
- 集合類型 — set, frozenset
- 映射類型 — dict
- 上下文管理器類型
- 其他內置類型
- 特殊屬性
- 內置異常
- 基類
- 具體異常
- 警告
- 異常層次結構
- 文本處理服務
- string — 常見的字符串操作
- re — 正則表達式操作
- 模塊 difflib 是一個計算差異的助手
- textwrap — Text wrapping and filling
- unicodedata — Unicode 數據庫
- stringprep — Internet String Preparation
- readline — GNU readline interface
- rlcompleter — GNU readline的完成函數
- 二進制數據服務
- struct — Interpret bytes as packed binary data
- codecs — Codec registry and base classes
- 數據類型
- datetime — 基礎日期/時間數據類型
- calendar — General calendar-related functions
- collections — 容器數據類型
- collections.abc — 容器的抽象基類
- heapq — 堆隊列算法
- bisect — Array bisection algorithm
- array — Efficient arrays of numeric values
- weakref — 弱引用
- types — Dynamic type creation and names for built-in types
- copy — 淺層 (shallow) 和深層 (deep) 復制操作
- pprint — 數據美化輸出
- reprlib — Alternate repr() implementation
- enum — Support for enumerations
- 數字和數學模塊
- numbers — 數字的抽象基類
- math — 數學函數
- cmath — Mathematical functions for complex numbers
- decimal — 十進制定點和浮點運算
- fractions — 分數
- random — 生成偽隨機數
- statistics — Mathematical statistics functions
- 函數式編程模塊
- itertools — 為高效循環而創建迭代器的函數
- functools — 高階函數和可調用對象上的操作
- operator — 標準運算符替代函數
- 文件和目錄訪問
- pathlib — 面向對象的文件系統路徑
- os.path — 常見路徑操作
- fileinput — Iterate over lines from multiple input streams
- stat — Interpreting stat() results
- filecmp — File and Directory Comparisons
- tempfile — Generate temporary files and directories
- glob — Unix style pathname pattern expansion
- fnmatch — Unix filename pattern matching
- linecache — Random access to text lines
- shutil — High-level file operations
- macpath — Mac OS 9 路徑操作函數
- 數據持久化
- pickle —— Python 對象序列化
- copyreg — Register pickle support functions
- shelve — Python object persistence
- marshal — Internal Python object serialization
- dbm — Interfaces to Unix “databases”
- sqlite3 — SQLite 數據庫 DB-API 2.0 接口模塊
- 數據壓縮和存檔
- zlib — 與 gzip 兼容的壓縮
- gzip — 對 gzip 格式的支持
- bz2 — 對 bzip2 壓縮算法的支持
- lzma — 用 LZMA 算法壓縮
- zipfile — 在 ZIP 歸檔中工作
- tarfile — Read and write tar archive files
- 文件格式
- csv — CSV 文件讀寫
- configparser — Configuration file parser
- netrc — netrc file processing
- xdrlib — Encode and decode XDR data
- plistlib — Generate and parse Mac OS X .plist files
- 加密服務
- hashlib — 安全哈希與消息摘要
- hmac — 基于密鑰的消息驗證
- secrets — Generate secure random numbers for managing secrets
- 通用操作系統服務
- os — 操作系統接口模塊
- io — 處理流的核心工具
- time — 時間的訪問和轉換
- argparse — 命令行選項、參數和子命令解析器
- getopt — C-style parser for command line options
- 模塊 logging — Python 的日志記錄工具
- logging.config — 日志記錄配置
- logging.handlers — Logging handlers
- getpass — 便攜式密碼輸入工具
- curses — 終端字符單元顯示的處理
- curses.textpad — Text input widget for curses programs
- curses.ascii — Utilities for ASCII characters
- curses.panel — A panel stack extension for curses
- platform — Access to underlying platform's identifying data
- errno — Standard errno system symbols
- ctypes — Python 的外部函數庫
- 并發執行
- threading — 基于線程的并行
- multiprocessing — 基于進程的并行
- concurrent 包
- concurrent.futures — 啟動并行任務
- subprocess — 子進程管理
- sched — 事件調度器
- queue — 一個同步的隊列類
- _thread — 底層多線程 API
- _dummy_thread — _thread 的替代模塊
- dummy_threading — 可直接替代 threading 模塊。
- contextvars — Context Variables
- Context Variables
- Manual Context Management
- asyncio support
- 網絡和進程間通信
- asyncio — 異步 I/O
- socket — 底層網絡接口
- ssl — TLS/SSL wrapper for socket objects
- select — Waiting for I/O completion
- selectors — 高級 I/O 復用庫
- asyncore — 異步socket處理器
- asynchat — 異步 socket 指令/響應 處理器
- signal — Set handlers for asynchronous events
- mmap — Memory-mapped file support
- 互聯網數據處理
- email — 電子郵件與 MIME 處理包
- json — JSON 編碼和解碼器
- mailcap — Mailcap file handling
- mailbox — Manipulate mailboxes in various formats
- mimetypes — Map filenames to MIME types
- base64 — Base16, Base32, Base64, Base85 數據編碼
- binhex — 對binhex4文件進行編碼和解碼
- binascii — 二進制和 ASCII 碼互轉
- quopri — Encode and decode MIME quoted-printable data
- uu — Encode and decode uuencode files
- 結構化標記處理工具
- html — 超文本標記語言支持
- html.parser — 簡單的 HTML 和 XHTML 解析器
- html.entities — HTML 一般實體的定義
- XML處理模塊
- xml.etree.ElementTree — The ElementTree XML API
- xml.dom — The Document Object Model API
- xml.dom.minidom — Minimal DOM implementation
- xml.dom.pulldom — Support for building partial DOM trees
- xml.sax — Support for SAX2 parsers
- xml.sax.handler — Base classes for SAX handlers
- xml.sax.saxutils — SAX Utilities
- xml.sax.xmlreader — Interface for XML parsers
- xml.parsers.expat — Fast XML parsing using Expat
- 互聯網協議和支持
- webbrowser — 方便的Web瀏覽器控制器
- cgi — Common Gateway Interface support
- cgitb — Traceback manager for CGI scripts
- wsgiref — WSGI Utilities and Reference Implementation
- urllib — URL 處理模塊
- urllib.request — 用于打開 URL 的可擴展庫
- urllib.response — Response classes used by urllib
- urllib.parse — Parse URLs into components
- urllib.error — Exception classes raised by urllib.request
- urllib.robotparser — Parser for robots.txt
- http — HTTP 模塊
- http.client — HTTP協議客戶端
- ftplib — FTP protocol client
- poplib — POP3 protocol client
- imaplib — IMAP4 protocol client
- nntplib — NNTP protocol client
- smtplib —SMTP協議客戶端
- smtpd — SMTP Server
- telnetlib — Telnet client
- uuid — UUID objects according to RFC 4122
- socketserver — A framework for network servers
- http.server — HTTP 服務器
- http.cookies — HTTP state management
- http.cookiejar — Cookie handling for HTTP clients
- xmlrpc — XMLRPC 服務端與客戶端模塊
- xmlrpc.client — XML-RPC client access
- xmlrpc.server — Basic XML-RPC servers
- ipaddress — IPv4/IPv6 manipulation library
- 多媒體服務
- audioop — Manipulate raw audio data
- aifc — Read and write AIFF and AIFC files
- sunau — 讀寫 Sun AU 文件
- wave — 讀寫WAV格式文件
- chunk — Read IFF chunked data
- colorsys — Conversions between color systems
- imghdr — 推測圖像類型
- sndhdr — 推測聲音文件的類型
- ossaudiodev — Access to OSS-compatible audio devices
- 國際化
- gettext — 多語種國際化服務
- locale — 國際化服務
- 程序框架
- turtle — 海龜繪圖
- cmd — 支持面向行的命令解釋器
- shlex — Simple lexical analysis
- Tk圖形用戶界面(GUI)
- tkinter — Tcl/Tk的Python接口
- tkinter.ttk — Tk themed widgets
- tkinter.tix — Extension widgets for Tk
- tkinter.scrolledtext — 滾動文字控件
- IDLE
- 其他圖形用戶界面(GUI)包
- 開發工具
- typing — 類型標注支持
- pydoc — Documentation generator and online help system
- doctest — Test interactive Python examples
- unittest — 單元測試框架
- unittest.mock — mock object library
- unittest.mock 上手指南
- 2to3 - 自動將 Python 2 代碼轉為 Python 3 代碼
- test — Regression tests package for Python
- test.support — Utilities for the Python test suite
- test.support.script_helper — Utilities for the Python execution tests
- 調試和分析
- bdb — Debugger framework
- faulthandler — Dump the Python traceback
- pdb — The Python Debugger
- The Python Profilers
- timeit — 測量小代碼片段的執行時間
- trace — Trace or track Python statement execution
- tracemalloc — Trace memory allocations
- 軟件打包和分發
- distutils — 構建和安裝 Python 模塊
- ensurepip — Bootstrapping the pip installer
- venv — 創建虛擬環境
- zipapp — Manage executable Python zip archives
- Python運行時服務
- sys — 系統相關的參數和函數
- sysconfig — Provide access to Python's configuration information
- builtins — 內建對象
- main — 頂層腳本環境
- warnings — Warning control
- dataclasses — 數據類
- contextlib — Utilities for with-statement contexts
- abc — 抽象基類
- atexit — 退出處理器
- traceback — Print or retrieve a stack traceback
- future — Future 語句定義
- gc — 垃圾回收器接口
- inspect — 檢查對象
- site — Site-specific configuration hook
- 自定義 Python 解釋器
- code — Interpreter base classes
- codeop — Compile Python code
- 導入模塊
- zipimport — Import modules from Zip archives
- pkgutil — Package extension utility
- modulefinder — 查找腳本使用的模塊
- runpy — Locating and executing Python modules
- importlib — The implementation of import
- Python 語言服務
- parser — Access Python parse trees
- ast — 抽象語法樹
- symtable — Access to the compiler's symbol tables
- symbol — 與 Python 解析樹一起使用的常量
- token — 與Python解析樹一起使用的常量
- keyword — 檢驗Python關鍵字
- tokenize — Tokenizer for Python source
- tabnanny — 模糊縮進檢測
- pyclbr — Python class browser support
- py_compile — Compile Python source files
- compileall — Byte-compile Python libraries
- dis — Python 字節碼反匯編器
- pickletools — Tools for pickle developers
- 雜項服務
- formatter — Generic output formatting
- Windows系統相關模塊
- msilib — Read and write Microsoft Installer files
- msvcrt — Useful routines from the MS VC++ runtime
- winreg — Windows 注冊表訪問
- winsound — Sound-playing interface for Windows
- Unix 專有服務
- posix — The most common POSIX system calls
- pwd — 用戶密碼數據庫
- spwd — The shadow password database
- grp — The group database
- crypt — Function to check Unix passwords
- termios — POSIX style tty control
- tty — 終端控制功能
- pty — Pseudo-terminal utilities
- fcntl — The fcntl and ioctl system calls
- pipes — Interface to shell pipelines
- resource — Resource usage information
- nis — Interface to Sun's NIS (Yellow Pages)
- Unix syslog 庫例程
- 被取代的模塊
- optparse — Parser for command line options
- imp — Access the import internals
- 未創建文檔的模塊
- 平臺特定模塊
- 擴展和嵌入 Python 解釋器
- 推薦的第三方工具
- 不使用第三方工具創建擴展
- 使用 C 或 C++ 擴展 Python
- 自定義擴展類型:教程
- 定義擴展類型:已分類主題
- 構建C/C++擴展
- 在Windows平臺編譯C和C++擴展
- 在更大的應用程序中嵌入 CPython 運行時
- Embedding Python in Another Application
- Python/C API 參考手冊
- 概述
- 代碼標準
- 包含文件
- 有用的宏
- 對象、類型和引用計數
- 異常
- 嵌入Python
- 調試構建
- 穩定的應用程序二進制接口
- The Very High Level Layer
- Reference Counting
- 異常處理
- Printing and clearing
- 拋出異常
- Issuing warnings
- Querying the error indicator
- Signal Handling
- Exception Classes
- Exception Objects
- Unicode Exception Objects
- Recursion Control
- 標準異常
- 標準警告類別
- 工具
- 操作系統實用程序
- 系統功能
- 過程控制
- 導入模塊
- Data marshalling support
- 語句解釋及變量編譯
- 字符串轉換與格式化
- 反射
- 編解碼器注冊與支持功能
- 抽象對象層
- Object Protocol
- 數字協議
- Sequence Protocol
- Mapping Protocol
- 迭代器協議
- 緩沖協議
- Old Buffer Protocol
- 具體的對象層
- 基本對象
- 數值對象
- 序列對象
- 容器對象
- 函數對象
- 其他對象
- Initialization, Finalization, and Threads
- 在Python初始化之前
- 全局配置變量
- Initializing and finalizing the interpreter
- Process-wide parameters
- Thread State and the Global Interpreter Lock
- Sub-interpreter support
- Asynchronous Notifications
- Profiling and Tracing
- Advanced Debugger Support
- Thread Local Storage Support
- 內存管理
- 概述
- 原始內存接口
- Memory Interface
- 對象分配器
- 默認內存分配器
- Customize Memory Allocators
- The pymalloc allocator
- tracemalloc C API
- 示例
- 對象實現支持
- 在堆中分配對象
- Common Object Structures
- Type 對象
- Number Object Structures
- Mapping Object Structures
- Sequence Object Structures
- Buffer Object Structures
- Async Object Structures
- 使對象類型支持循環垃圾回收
- API 和 ABI 版本管理
- 分發 Python 模塊
- 關鍵術語
- 開源許可與協作
- 安裝工具
- 閱讀指南
- 我該如何...?
- ...為我的項目選擇一個名字?
- ...創建和分發二進制擴展?
- 安裝 Python 模塊
- 關鍵術語
- 基本使用
- 我應如何 ...?
- ... 在 Python 3.4 之前的 Python 版本中安裝 pip ?
- ... 只為當前用戶安裝軟件包?
- ... 安裝科學計算類 Python 軟件包?
- ... 使用并行安裝的多個 Python 版本?
- 常見的安裝問題
- 在 Linux 的系統 Python 版本上安裝
- 未安裝 pip
- 安裝二進制編譯擴展
- Python 常用指引
- 將 Python 2 代碼遷移到 Python 3
- 簡要說明
- 詳情
- 將擴展模塊移植到 Python 3
- 條件編譯
- 對象API的更改
- 模塊初始化和狀態
- CObject 替換為 Capsule
- 其他選項
- Curses Programming with Python
- What is curses?
- Starting and ending a curses application
- Windows and Pads
- Displaying Text
- User Input
- For More Information
- 實現描述器
- 摘要
- 定義和簡介
- 描述器協議
- 發起調用描述符
- 描述符示例
- Properties
- 函數和方法
- Static Methods and Class Methods
- 函數式編程指引
- 概述
- 迭代器
- 生成器表達式和列表推導式
- 生成器
- 內置函數
- itertools 模塊
- The functools module
- Small functions and the lambda expression
- Revision History and Acknowledgements
- 引用文獻
- 日志 HOWTO
- 日志基礎教程
- 進階日志教程
- 日志級別
- 有用的處理程序
- 記錄日志中引發的異常
- 使用任意對象作為消息
- 優化
- 日志操作手冊
- 在多個模塊中使用日志
- 在多線程中使用日志
- 使用多個日志處理器和多種格式化
- 在多個地方記錄日志
- 日志服務器配置示例
- 處理日志處理器的阻塞
- Sending and receiving logging events across a network
- Adding contextual information to your logging output
- Logging to a single file from multiple processes
- Using file rotation
- Use of alternative formatting styles
- Customizing LogRecord
- Subclassing QueueHandler - a ZeroMQ example
- Subclassing QueueListener - a ZeroMQ example
- An example dictionary-based configuration
- Using a rotator and namer to customize log rotation processing
- A more elaborate multiprocessing example
- Inserting a BOM into messages sent to a SysLogHandler
- Implementing structured logging
- Customizing handlers with dictConfig()
- Using particular formatting styles throughout your application
- Configuring filters with dictConfig()
- Customized exception formatting
- Speaking logging messages
- Buffering logging messages and outputting them conditionally
- Formatting times using UTC (GMT) via configuration
- Using a context manager for selective logging
- 正則表達式HOWTO
- 概述
- 簡單模式
- 使用正則表達式
- 更多模式能力
- 修改字符串
- 常見問題
- 反饋
- 套接字編程指南
- 套接字
- 創建套接字
- 使用一個套接字
- 斷開連接
- 非阻塞的套接字
- 排序指南
- 基本排序
- 關鍵函數
- Operator 模塊函數
- 升序和降序
- 排序穩定性和排序復雜度
- 使用裝飾-排序-去裝飾的舊方法
- 使用 cmp 參數的舊方法
- 其它
- Unicode 指南
- Unicode 概述
- Python's Unicode Support
- Reading and Writing Unicode Data
- Acknowledgements
- 如何使用urllib包獲取網絡資源
- 概述
- Fetching URLs
- 處理異常
- info and geturl
- Openers and Handlers
- Basic Authentication
- Proxies
- Sockets and Layers
- 腳注
- Argparse 教程
- 概念
- 基礎
- 位置參數介紹
- Introducing Optional arguments
- Combining Positional and Optional arguments
- Getting a little more advanced
- Conclusion
- ipaddress模塊介紹
- 創建 Address/Network/Interface 對象
- 審查 Address/Network/Interface 對象
- Network 作為 Address 列表
- 比較
- 將IP地址與其他模塊一起使用
- 實例創建失敗時獲取更多詳細信息
- Argument Clinic How-To
- The Goals Of Argument Clinic
- Basic Concepts And Usage
- Converting Your First Function
- Advanced Topics
- 使用 DTrace 和 SystemTap 檢測CPython
- Enabling the static markers
- Static DTrace probes
- Static SystemTap markers
- Available static markers
- SystemTap Tapsets
- 示例
- Python 常見問題
- Python常見問題
- 一般信息
- 現實世界中的 Python
- 編程常見問題
- 一般問題
- 核心語言
- 數字和字符串
- 性能
- 序列(元組/列表)
- 對象
- 模塊
- 設計和歷史常見問題
- 為什么Python使用縮進來分組語句?
- 為什么簡單的算術運算得到奇怪的結果?
- 為什么浮點計算不準確?
- 為什么Python字符串是不可變的?
- 為什么必須在方法定義和調用中顯式使用“self”?
- 為什么不能在表達式中賦值?
- 為什么Python對某些功能(例如list.index())使用方法來實現,而其他功能(例如len(List))使用函數實現?
- 為什么 join()是一個字符串方法而不是列表或元組方法?
- 異常有多快?
- 為什么Python中沒有switch或case語句?
- 難道不能在解釋器中模擬線程,而非得依賴特定于操作系統的線程實現嗎?
- 為什么lambda表達式不能包含語句?
- 可以將Python編譯為機器代碼,C或其他語言嗎?
- Python如何管理內存?
- 為什么CPython不使用更傳統的垃圾回收方案?
- CPython退出時為什么不釋放所有內存?
- 為什么有單獨的元組和列表數據類型?
- 列表是如何在CPython中實現的?
- 字典是如何在CPython中實現的?
- 為什么字典key必須是不可變的?
- 為什么 list.sort() 沒有返回排序列表?
- 如何在Python中指定和實施接口規范?
- 為什么沒有goto?
- 為什么原始字符串(r-strings)不能以反斜杠結尾?
- 為什么Python沒有屬性賦值的“with”語句?
- 為什么 if/while/def/class語句需要冒號?
- 為什么Python在列表和元組的末尾允許使用逗號?
- 代碼庫和插件 FAQ
- 通用的代碼庫問題
- 通用任務
- 線程相關
- 輸入輸出
- 網絡 / Internet 編程
- 數據庫
- 數學和數字
- 擴展/嵌入常見問題
- 可以使用C語言中創建自己的函數嗎?
- 可以使用C++語言中創建自己的函數嗎?
- C很難寫,有沒有其他選擇?
- 如何從C執行任意Python語句?
- 如何從C中評估任意Python表達式?
- 如何從Python對象中提取C的值?
- 如何使用Py_BuildValue()創建任意長度的元組?
- 如何從C調用對象的方法?
- 如何捕獲PyErr_Print()(或打印到stdout / stderr的任何內容)的輸出?
- 如何從C訪問用Python編寫的模塊?
- 如何從Python接口到C ++對象?
- 我使用Setup文件添加了一個模塊,為什么make失敗了?
- 如何調試擴展?
- 我想在Linux系統上編譯一個Python模塊,但是缺少一些文件。為什么?
- 如何區分“輸入不完整”和“輸入無效”?
- 如何找到未定義的g++符號__builtin_new或__pure_virtual?
- 能否創建一個對象類,其中部分方法在C中實現,而其他方法在Python中實現(例如通過繼承)?
- Python在Windows上的常見問題
- 我怎樣在Windows下運行一個Python程序?
- 我怎么讓 Python 腳本可執行?
- 為什么有時候 Python 程序會啟動緩慢?
- 我怎樣使用Python腳本制作可執行文件?
- *.pyd 文件和DLL文件相同嗎?
- 我怎樣將Python嵌入一個Windows程序?
- 如何讓編輯器不要在我的 Python 源代碼中插入 tab ?
- 如何在不阻塞的情況下檢查按鍵?
- 圖形用戶界面(GUI)常見問題
- 圖形界面常見問題
- Python 是否有平臺無關的圖形界面工具包?
- 有哪些Python的GUI工具是某個平臺專用的?
- 有關Tkinter的問題
- “為什么我的電腦上安裝了 Python ?”
- 什么是Python?
- 為什么我的電腦上安裝了 Python ?
- 我能刪除 Python 嗎?
- 術語對照表
- 文檔說明
- Python 文檔貢獻者
- 解決 Bug
- 文檔錯誤
- 使用 Python 的錯誤追蹤系統
- 開始為 Python 貢獻您的知識
- 版權
- 歷史和許可證
- 軟件歷史
- 訪問Python或以其他方式使用Python的條款和條件
- Python 3.7.3 的 PSF 許可協議
- Python 2.0 的 BeOpen.com 許可協議
- Python 1.6.1 的 CNRI 許可協議
- Python 0.9.0 至 1.2 的 CWI 許可協議
- 集成軟件的許可和認可
- Mersenne Twister
- 套接字
- Asynchronous socket services
- Cookie management
- Execution tracing
- UUencode and UUdecode functions
- XML Remote Procedure Calls
- test_epoll
- Select kqueue
- SipHash24
- strtod and dtoa
- OpenSSL
- expat
- libffi
- zlib
- cfuhash
- libmpdec