Python標準庫筆記(1) — string模組
目錄[-]
String模組包含大量實用常量和類,以及一些過時的遺留功能,並還可用作字串操作。
1. 常用方法
常用方法 |
描述 |
---|---|
str.capitalize() |
把字串的首字母大寫 |
str.center(width) |
將原字串用空格填充成一個長度為width的字串,原字串內容居中 |
str.count(s) |
返回字串s在str中出現的次數 |
str.decode(encoding='UTF-8',errors='strict') |
以指定編碼格式解碼字串 |
str.encode(encoding='UTF-8',errors='strict') |
以指定編碼格式編碼字串 |
str.endswith(s) |
判斷字串str是否以字串s結尾 |
str.find(s) |
返回字串s在字串str中的位置索引,沒有則返回-1 |
str.index(s) |
和find()方法一樣,但是如果s不存在於str中則會丟擲異常 |
str.isalnum() |
如果str至少有一個字元並且都是字母或數字則返回True,否則返回False |
str.isalpha() |
如果str至少有一個字元並且都是字母則返回True,否則返回False |
str.isdigit() |
如果str只包含數字則返回 True 否則返回 False |
str.islower() |
如果str存在區分大小寫的字元,並且都是小寫則返回True 否則返回False |
str.isspace() |
如果str中只包含空格,則返回 True,否則返回 False |
str.istitle() |
如果str是標題化的(單詞首字母大寫)則返回True,否則返回False |
str.isupper() |
如果str存在區分大小寫的字元,並且都是大寫則返回True 否則返回False |
str.ljust(width) |
返回一個原字串左對齊的並使用空格填充至長度width的新字串 |
str.lower() |
轉換str中所有大寫字元為小寫 |
str.lstrip() |
去掉str左邊的不可見字元 |
str.partition(s) |
用s將str切分成三個值 |
str.replace(a, b) |
將字串str中的a替換成b |
str.rfind(s) |
類似於 find()函式,不過是從右邊開始查詢 |
str.rindex(s) |
類似於 index(),不過是從右邊開始 |
str.rjust(width) |
返回一個原字串右對齊的並使用空格填充至長度width的新字串 |
str.rpartition(s) |
類似於 partition()函式,不過是從右邊開始查詢 |
str.rstrip() |
去掉str右邊的不可見字元 |
str.split(s) |
以s為分隔符切片str |
str.splitlines() |
按照行分隔,返回一個包含各行作為元素的列表 |
str.startswith(s) |
檢查字串str是否是以s開頭,是則返回True,否則返回False |
str.strip() |
等於同時執行rstrip()和lstrip() |
str.title() |
返回"標題化"的str,所有單詞都是以大寫開始,其餘字母均為小寫 |
str.upper() |
返回str所有字元為大寫的字串 |
str.zfill(width) |
返回長度為 width 的字串,原字串str右對齊,前面填充0 |
2.字串常量
常數 |
含義 |
---|---|
string.ascii_lowercase |
小寫字母'abcdefghijklmnopqrstuvwxyz' |
string.ascii_uppercase |
大寫的字母'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
string.ascii_letters |
ascii_lowercase和ascii_uppercase常量的連線串 |
string.digits |
數字0到9的字串:'0123456789' |
string.hexdigits |
字串'0123456789abcdefABCDEF' |
string.letters |
字串'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' |
string.lowercase |
小寫字母的字串'abcdefghijklmnopqrstuvwxyz' |
string.octdigits |
字串'01234567' |
string.punctuation |
所有標點字元 |
string.printable |
可列印的字元的字串。包含數字、字母、標點符號和空格 |
string.uppercase |
大學字母的字串'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
string.whitespace |
空白字元 'tnx0bx0cr ' |
3.字串模板Template
通過string.Template可以為Python定製字串的替換標準,下面是具體列子:
>>>from string import Template
>>>s = Template('$who like $what')
>>>print s.substitute(who='i', what='python')
i like python
>>>print s.safe_substitute(who='i') # 缺少key時不會拋錯
i like $what
>>>Template('${who}LikePython').substitute(who='I') # 在字串內時使用{}
'ILikePython'
Template還有更加高階的用法,可以通過繼承string.Template, 重寫變數delimiter(定界符)和idpattern(替換格式), 定製不同形式的模板。
import string
template_text = '''
Delimiter : $de
Replaced : %with_underscore
Ingored : %notunderscored
'''
d = {'de': 'not replaced',
'with_underscore': 'replaced',
'notunderscored': 'not replaced'}
class MyTemplate(string.Template):
# 重寫模板 定界符(delimiter)為"%", 替換模式(idpattern)必須包含下劃線(_)
delimiter = '%'
idpattern = '[a-z]+_[a-z]+'
print string.Template(template_text).safe_substitute(d) # 採用原來的Template渲染
print MyTemplate(template_text).safe_substitute(d) # 使用重寫後的MyTemplate渲染
輸出:
Delimiter : not replaced
Replaced : %with_underscore
Ingored : %notunderscored
Delimiter : $de
Replaced : replaced
Ingored : %notunderscored
原生的Template只會渲染界定符為$的情況,重寫後的MyTemplate會渲染界定符為%且替換格式帶有下劃線的情況。
4.常用字串技巧
- 1.反轉字串
>>> s = '1234567890'
>>> print s[::-1]
0987654321
- 2.關於字串連結
儘量使用join()連結字串,因為'+'號連線n個字串需要申請n-1次記憶體,使用join()需要申請1次記憶體。
- 3.固定長度分割字串
>>> import re
>>> s = '1234567890'
>>> re.findall(r'.{1,3}', s) # 已三個長度分割字串
['123', '456', '789', '0']
- 4.使用()括號生成字串
sql = ('SELECT count() FROM table '
'WHERE id = "10" '
'GROUP BY sex')
print sql
SELECT count() FROM table WHERE id = "10" GROUP BY sex
- 5.將print的字串寫到檔案
>>> print >> open("somefile.txt", "w+"), "Hello World" # Hello World將寫入檔案somefile.txt