字符串
1、字符串拼接办法:
(1)用%拼接: "aaa%sbbb" % 'f'
(2)用join()方法拼接:
>>> a ['d', 'f', 'g'] >>> ''.join(a) 'dfg'
>>> a=['a','b','c'] #必须是字符串 >>> b.join(a) 'a+b+c'
>>> dir='','usr','local','bin' >>> '/'.join(dir) '/usr/local/bin'
(3)用format()方法拼接:
>>> tr="there is {},{},{} on the table"
>>> tr.format('z','v','b')
'there is z,v,b on the table'
(4)用string模块中的Template对象:
from string import Template
>>> s=Template("aaa${x}bbb")
>>> s.substitute(x='f')
'aaafbbb'
2、字符串方法:
(1)find方法可以在一个较长的字符串中查找子字符串。它返回子串所在位置的最左端索引,没找到返回-1;
>>> a="adfghre" >>> a.find('d') 1 >>> a.find('i') -1
指定起始位置和结束位置 >>>a.find('e',1,7) 6
(2)join和split都是很重要的字符串方法,互为逆方法。
注意:需要添加的队列元素都必须是字符串。
join用来连接字符串;
>>> dir='','usr','local','bin'
>>> print 'C:' + '\\'.join(dir) >>> print 'C:' + '/'.join(dir)
C:/usr/local/bin C:\usr\local\bin
split用来将字符串分割成序列。
>>> s
'C:/usr/local/bin'
>>> s.split('/')
['C:', 'usr', 'local', 'bin']
(3)lower方法返回字符串的小写字母版。
>>> "DfF".lower() 'dff'
title方法可以将首字母变成大写:
>>> "a name NdG".title() 'A Name Ndg'
string里有个capwords函数:
>>> import string >>> string.capwords("it is a dog") 'It Is A Dog'
(4)replace方法返回某字符串的所有匹配项均被替换之后的得到的字符串。
>>> ("it is a dog").replace('dog','pig') 'it is a pig'
(5)strip方法返回去除两侧(不包括内部)空格的字符串,lstrip、rstrip分别去除左右两边的空格。
>>> ("g f f ").strip() 'g f f'
如果想去除字符串中所有的空格可用replace替换空格为空:
>>> (" g f f ").replace(' ','') 'gff'
strip也可以指定要去除的字符:
>>> ("####fff k * &&").strip('#&') 'fff k * '
3、函数:string.maketrans(from,to)创建用于转换的转换表。
提取全部小写字母
>>> maketrans('','')[97:123]
'abcdefghijklmnopqrstuvwxyz'
生成一个替换表:
>>> table =maketrans('a','b')
>>> table[97:123]
'bbcdefghijklmnopqrstuvwxyz'