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 | 空白字符 ‘\t\n\x0b\x0c\r ‘ |
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