字符串:
1、字符串不可变
>>> a
'this is a test'>>> a[0:3]
'thi'
>>> a[0]='1'
Traceback (most recent call last):
File "<pyshell#96>", line 1, in <module>
a[0]='1'
TypeError: 'str' object does not support item assignment
>>>
2、使用元组对字符串格式化:
>>> "this is a %s %s" % ("python","programer")
'this is a python programer'
>>> from math import pi
>>> "%s is %.10f" % ("pi",pi)
'pi is 3.1415926536'
使用string 中的 Tamplate 模板替换
>>> from string import Template
>>> s=Template("$$,${x}is,is test")
>>> s.substitute(x='th')
'$,this,is test'
>>> "%s is %020.10f" % ("pi",pi)
'pi is 000000003.1415926536'
>>> "%s is %-020.10f" % ("pi",pi)
'pi is 3.1415926536 '
>>>
3、字符串中的常量
string.digits 0-9数字
.letters 所有字母
.lowercase 所有小写字母
.uppercase 所有大写字母
.punctutation 所有标点符号
引用方法:
>>> from string import digits as d
>>> d
'0123456789'
4、find方法:返回要找字符串最左端的位置,没有找到则返回-1
>>> "this is the test".find("is")
2
>>> "this is the test".find("she")
-1
5、join方法:字符串连接方法,格式:连接字符串.join(["字符串元素1","字符串元素1","字符串元素1"]). 注意连接符和列表元素必须都为字符串. 返回一个连接后的字符串,它的反方法为split
>>> a=["this","is","the","test"]
>>> " ".join(a)
'this is the test'
>>> a=[1,2,3]
>>> " ".join(a)
Traceback (most recent call last):
File "<pyshell#124>", line 1, in <module>
" ".join(a)
TypeError: sequence item 0: expected string, int found
>>> "the".join(["this","is"])
'thistheis'
>>>
6、split方法:'需要拆分的字符串'.split('拆分字符串的标志符') 返回一个列表
>>> 'this is the test'.split(' ')
['this', 'is', 'the', 'test']
>>> '0+2+4+6+8'.split('+')
['0', '2', '4', '6', '8']
>>>
7、lower()方法:将字符串中的大写字母转换成小写字母
>>> "This Is thE TEsT".lower()
'this is the test'
8、replace方法:格式 字符串.replace('原子符','替代字符')
>>> "This Is thE TEsT".lower().replace('is','ezz') %从左往右计算
'thezz ezz the test'
9、strip方法:把两边的空格符删除
>>> ' this is the test '.strip()
'this is the test'
10、另一种替换方法,单字符替换方法 translate,格式先用maketrans制作表,然后在进行替换
>>> from string import maketrans
>>> table=maketrans('cs','kz') %c变为k, s变为z
>>> 'this is a test'.translate(table)
'thiz iz a tezt'
>>> 'thiS is a test cd..'.translate(table)
'thiS iz a tezt kd..'