Python 学习笔记(三) 使用字符串


3.1 字符串基本操作


所有标准的序列操作(索引,分片,乘法,判断成员资格...)对字符串同样适用. 但是,请牢记字符串都是不可改变的


3.2 字符串格式化:精简版


初次接触python编程,所用到的字符串格式化内容并不多, 这里仅略微举例, 大致感受一下即可:

>>> format = " Hello,%s,%s enough for ya ?"
>>> values = ('world','hot')
>>> print format % values
 Hello,world,hot enough for ya ?

3.3 字符串格式化 : 完整版

先跳过.


3.4 字符串方法


字符串方法很多(就如C++ 中的 string一样) 这里只介绍一些特别有用的


3.4.1 find

在一个较长的字符串中查找子字符串. 他返回子串所在位置的最左端索引,如果没有找到则返回-1.

>>> 'With a moo-moo here,and a moo-moo there '.find('moo')
7
>>> title = "Monty Python"s Flying Circus"
>>> title.find('Monty')
0
>>> title.find('daxiao')
-1

这个方法还可以选择可选的起始点和结束点参数

>>> subject = '$$$ Get rich now !!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$',1)
21
>>> subject.find('!!!',0,4)
-1

3.4.2 join

join 方法是非常重要的字符串方法, 它是split方法的逆方法, 同来在队列中添加元素.

>>> seq= [1,2,3,4,5]
>>> sep= '+'
>>> sep.join(seq)

Traceback (most recent call last):
  File "", line 1, in 
    sep.join(seq)
TypeError: sequence item 0: expected string, int found
>>> seq=['1','2','3','4','5']
>>> sep.join(seq)
'1+2+3+4+5'
可以看到,需要添加的队列元素都必须是字符串.


3.4.3 lower

lower 方法返回字符串的小写字母版

>>> ' Hello ! World '.lower()
' hello ! world '

3.4.4 replace

返回某个字符串的所有匹配项都被替换后的字符串

>>> 'This is a test' .replace ('is','eez')
'Theez eez a test'

3.4.5 split

这是一个非常重要的字符串方法,它是join方法的逆方法,用来将字符串分割成序列.

>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']

如果不提供分隔符,程序会把所有空格作为分隔符.


3.4.6 strip

strip 方法返回去除两侧空格的字符串:

>>> '      internal whitespace is kept      '.strip()
'internal whitespace is kept'

3.4.7 translate

translate 方法和replace方法一样 .可以替换字符串中的某些部分.但是和前者不同的是.translate方法只能处理单个字符. 它的优势在可以同时进行多个替换,有时比replacee效率高得多.

在使用translate转化之前,先要完成一张转换表. 这里可以使用string 模块里面的maketrans函数.

maketrans函数需要两个参数: 两个等长的字符串,表示第一个字符串中的每个字符都用第二个字符串中相同位置的字符替换.


>>> from string import maketrans
>>> table = maketrans ('cs','kz')
>>> ' this is an incredible test '.translate(table)
' thiz iz an inkredible tezt '

trans第二个参数是可选的,这个参数用来指定需要删除的字符.

>>> 'this is an incredible test'.translate(table ,' ')
'thizizaninkredibletezt'


小结

字符串格式化:

字符串方法

评论关闭