国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

詳解Python中的文本處理

2020-02-23 00:39:17
字體:
來源:轉載
供稿:網友

字符串 -- 不可改變的序列

如同大多數高級編程語言一樣,變長字符串是 Python 中的基本類型。Python 在“后臺”分配內存以保存字符串(或其它值),程序員不必為此操心。Python 還有一些其它高級語言沒有的字符串處理功能。

在 Python 中,字符串是“不可改變的序列”。盡管不能“按位置”修改字符串(如字節組),但程序可以引用字符串的元素或子序列,就象使用任何序列一樣。Python 使用靈活的“分片”操作來引用子序列,字符片段的格式類似于電子表格中一定范圍的行或列。以下交互式會話說明了字符串和字符片段的的用法:
字符串和分片

>>> s =     "mary had a little lamb">>> s[0]     # index is zero-based    'm'>>> s[3] =     'x'     # changing element in-place failsTraceback (innermost last): File     "<stdin>", line 1,     in     ?TypeError: object doesn't support item assignment>>> s[11:18]     # 'slice' a subsequence    'little '>>> s[:4]     # empty slice-begin assumes zero    'mary'>>> s[4]     # index 4 is not included in slice [:4]    ' '>>> s[5:-5]     # can use "from end" index with negatives    'had a little'>>> s[:5]+s[5:]     # slice-begin & slice-end are complimentary    'mary had a little lamb'

另一個功能強大的字符串操作就是簡單的 in 關鍵字。它提供了兩個直觀有效的構造:
in 關鍵字

>>> s =     "mary had a little lamb">>>     for     c     in     s[11:18]:     print     c,     # print each char in slice...l i t t l e>>>     if    'x'     in     s:     print    'got x'     # test for char occurrence...>>>     if    'y'     in     s:     print    'got y'     # test for char occurrence...got y

在 Python 中,有幾種方法可以構成字符串文字。可以使用單引號或雙引號,只要左引號和右引號匹配,常用的還有其它引號的變化形式。如果字符串包含換行符或嵌入引號,三重引號可以很方便地定義這樣的字符串,如下例所示:
三重引號的使用

>>> s2 =     """Mary had a little lamb... its fleece was white as snow... and everywhere that Mary went... the lamb was sure to go""">>>     print     s2Mary had a little lambits fleece was white as snow    and     everywhere that Mary wentthe lamb was sure to go

使用單引號或三重引號的字符串前面可以加一個字母 "r" 以表示 Python 不應該解釋規則表達式特殊字符。例如:
使用 "r-strings"

>>> s3 =     "this /n and /n that">>>     print     s3this    and    that>>> s4 = r    "this /n and /n that">>>     print     s4this /n     and     /n that            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 密山市| 九台市| 宾阳县| 鹿泉市| 香河县| 同德县| 长乐市| 马山县| 靖西县| 天等县| 桂平市| 长垣县| 黑龙江省| 铁岭市| 洛南县| 修水县| 房产| 稻城县| 永康市| 罗城| 绩溪县| 南昌市| 澄迈县| 卫辉市| 磐石市| 高尔夫| 崇文区| 南澳县| 莲花县| 皮山县| 江西省| 日土县| 南漳县| 盘锦市| 寻乌县| 霍邱县| 溆浦县| 荆州市| 增城市| 邮箱| 邵阳市|