查漏补缺(三)——使用字符串

  模板字符串: 

string模块提供另一种格式化值的方法:模板字符串。它的工作方式类似于很多UNIXShell里的变量替换。

如下所示,substitute这个模块方法会用传递进来的关键字参数foo替换字符串中的$foo :

>>>from string import Template
>>>s=Template('$x,glorious $x!')
>>>s.substitute(x='slurm')
'slurm,glorious slurm!‘ 

如果替换字段是单词的一部分,那么参数名就必须用括号括起来,从而准备指明结尾:

可以使用$$插入美元符号:

>>>s=Template("It's ${x}tastic!")
>>>s.substitute(x='slurm')
"It's slurmtastic!"

除了关键字参数之外,还可以使用字典提供值/名称对:

>>>s=Template('A $thing must never $action.')
>>>d={}
>>>d['thing']='gentleman'
>>>d['action']='show his socks'
>>>s.substitute(d)
'A gentleman must never show his socks.'

3.4.1 find

        find方法可以在一个较长的字符串中查找子串。它返回子串所在位置的最左端索引。如果没有找到则返回-1。

3.4.2 join

        join方法是非常重要的字符串方法,它是split方法的逆方法,用来连接序列中的恶元素:

>>>seq=[1,2,3,4,5]
>>>sep='+'
>>>sep.join(seq) #连接数字列表
Traceback (most recent call last):
 File "<stdin>",line 1,in ?
TypeError: sequence item 0:expected string,int found
>>>seq=['1','2','3','4','5']
>>>sep,join(seq)#连接字符串列表
‘1+2+3+4+5>>>dirs='','usr','bin','env'
>>>'/'.join(dirs)
'/usr/bin/env'
>>>print 'C:'+'\'.join(dirs)
C:usrinenv

3.4.3 lower

>>>'that's all folks".title() #title方法
"That'S All.Folks"
>>>import string
>>>string.capwords("that's all. folks")
"That's All. Folks“

3.4.4 replace

3.4.5 split:是join的逆方法

3.4.6 strip:返回去除两侧(不包括内部)空格的字符串

3.4.7 translate:

         translate方法和replace方法一样,可以替换字符串中的某些部分,但和前者不同的是,

         translate方法只处理单个字符,它的优势在于可以同时进行多个替换,有些时候比replace效率高得多。

         在使用translate转换之前,需要先完成一张转换表。

        转换表是包含替换ASCII字符集中256个字符的替换字母的字符串。

原文地址:https://www.cnblogs.com/HelloDreams/p/4980438.html