序列中的字符串
字符串是序列的一种,序列的基本操作字符串都可以使用。
序列的基本操作有8种,索引,分片,加,乘,检查成员资格(in),计算序列长,找出最小最大元素
格式化字符串可以是任意类型,这里使用元组 ( , , )
如果使用元组,则其中的每一个元素都会被单独格式化
①%字符 转换说明符的开始
②转换标志 -表示左对齐,+表示转换值之前要加上正负号,“ ”正数之前保留空格,0表示位数不够用0填充
③最小字段宽度 转换后的字符串至少具有指定的宽度,为*从值元组读出
④(.)后跟精度值 若为实数,则表示小数点后的位数;若为字符串,该字数表示最大字段宽度
⑤转换类型
d,i 带符号十进制
o 不带符号八进制
u 不带符号十进制
x 不带符号十六进制(小写)
X 不带符号十六进制(大写)
e 科学计数法浮点数(小写)
E 科学计数法浮点数(大写)
f,F 十进制浮点数
g/G 如果指数大于-4或者小于精度值则和e/E相同,其他情况和f/F相同
C 接受证书或者单字符字符串
r repr(使用repr转换Python对象)
s str(使用str转换Python对象)
示例: 输出
print 'Using str: %s' % 42L Using str:42
print 'Using repr: %r' % 42L Using repr:42L
print '%.5s'% 'Guido van Rossum' Guido
print '%.*s'%(5,'Guido van Rossum' Guido
另外的一个格式字符串方法-------模板字符串
相当于利用了string.subtitute()方法
示例 -------------输出
from string import Template
s = Template('$x, glorious $x!')
print s.substitute(x = 'slurm') #该方法并不返回一个Template对象
'slurm, glorious slurm’
若替换字段是单词的一部分
s = Template('It's $[x]tastic!')
print s.substitute(x='slurm') 'It's slurmtastic!'
s = Template('A $thing must never $action')
d = {}
d['thing'] = 'gentleman'
d['action'] = 'show his socks'
print s.substitute(d) 'A gentleman must never show his socks.'
字符串方法------string
import string
string.digits#包含数字0~9的字符串
string.letters#包含所有字母(大写或小写的字符串)
string.lowercase#包含所有小写字母的字符串
string.uppercase#包含所有大写字母的字符串
string.printable#包含所有可打印字符的字符串
string.punctuation#包含所有标点的字符串
字符串方法
1.str.find(str,[A,B]])方法#作用可以在一个较长的字符串中查找子串,它返回子串所在位置的最左端索引
**由起止和终止值指定的范围(第二个和第三个参数)包含第一个索引,但不包含第二个索引
示例:-------输出
subject = '$$$ Get rich now!!! $$$'
print subject.find('!!!')16
print subject.find('!!!',0,16) -1 #在subject未找到‘!!!’
2.str.join(sequence) #作用用str中的字符串链接sequence(序列)注意序列元素必须是字符串
示例:
seq = ['1','2','3','4','5']
sep = '+'
print sep.join(seq) 1+2+3+4+5
3.str.lower()/str.upper()#作用将str中存储的字符串全部转换为小写/大写
示例:
name = 'Gumby'
names = ['gumby','smith','jones']
if name,lower in names : print 'Found it' 'Found it'
3.str.title() && string.capwords()#作用将字符串中所有单词的首字母转换为大写
示例:
test = 'That's all forks.'
print test.title() That'S All Forks.
import string
print test.capwords() That'S All Forks.
3.string.replace() #返回某字符串的所有匹配项被替换后得到的字符串
print 'This is a test'.replace('is','eez') 'Theez eez a test'
#注意单词中含有'is'也会被替换
4.str.split(str) #用来将字符串分割成序列
print ‘1+2+3+4+5’.split('+') ['1','2','3','4','5']
5.str.strip(str_par) #用来去掉字符串两端的str_par所指定的字符,默认为空格(‘ ’)
示例
print ‘*** SPAM * for * everyone!!! ***’.strip(' *!') 'SPAM * for everyone'
5.str.translate(table[,str]) #table为字母转化表通过maketrans(str,str)得到,第二个参数可选为需要删除的字符
string.maketrans(str,str) #接受两个等长的字符串,将第一个字符串中的每个字符都用第二个字符串中相同位置的字符替换,返回一个字符串
示例
from string import maketrans
table = maketrans('cs','ez')
print 'this is an incredible test.'.translate(table,' ') 'thizizaninkredibletezt'