與其它幾種流行的指令碼語言一樣,Python 是一種用於瀏覽和處理文本資料的優秀工具。本文為 Python 的初學者概述了 Python 的文本處理工具。文章說明了規則運算式的一些常規概念,並提供了處理文本時,什麼情況下應使用(或不使用)規則運算式的建議。
什麼是 Python?
Python 是由 Guido van Rossum 開發的、可免費獲得的、非常進階的解釋型語言。其文法簡單易懂,而其物件導向的語義功能強大(但又靈活)。Python 可以廣泛使用並具有高度的可移植性。
字串 -- 不可改變的序列
如同大多數進階程式設計語言一樣,變長字串是 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 fails
Traceback (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'