介绍:string模块可以追溯到最早的Python版本中。现在很多的被移植为str和unicode对象的方法,在python3.0中会被完全去除。string模块中,有很多有用的常量和累,用来处理string和unicode对象。

一、 函数

  1、capwords()的作用是将一个字符串中所有单词的首字母大写;

 import string
s = 'We believe one thing,today is difficult,tomorrow is more difficult,but the day after tomorrow is beautiful'
print s
print string.capwords(s)
print string.capwords(s,',')

执行结果:
We believe one thing,today is difficult,tomorrow is more difficult,but the day after tomorrow is beautiful
We Believe One Thing,today Is Difficult,tomorrow Is More Difficult,but The Day After Tomorrow Is Beautiful
We believe one thing,Today is difficult,Tomorrow is more difficult,but the day after tomorrow is beautiful

capwords(s,seq) 中可以传递两个参数,第一个是需要处理的字符串;第二个是使用什么条件进行拆分(默认空格);

该函数的工作原理死,先使用split拆分转变为大写以后,在使用join结合。

  2、maketrans()函数将创建转换表,可以用来结合translate()方法将一组字符串修改为另一组字符

 import string
s = 'We believe one thing,today is difficult,tomorrow is more difficult,but the day after tomorrow is beautiful'
leet = string.maketrans('abegiloprstz', '')
print s
print s.translate(leet)

执行结果:

We believe one thing,today is difficult,tomorrow is more difficult,but the day after tomorrow is beautiful
W3 63113v3 0n3 7h1n6,70d4y 15 d1ff1cu17,70m0220w 15 m023 d1ff1cu17,6u7 7h3 d4y 4f732 70m0220w 15 634u71fu1

maketrans(fromstr, tostr)中需必须传递两个参数,第一个是需要替换的字符,第二个是替换成为什么字符,需要注意的是两个字符串必须长度相同,否则会报异常。

二 模板

  主要使用的是string.Template拼接,变量可以使用前缀$ 来标识($var)或者使用大括号进行区分(${var})

   1、下面做一个模板和使用%操作符的比较

 import string
val = {'var':'Victory'}
t = string.Template("""
Variable : $var
Escape : $var
Variable in text : ${var}iable
""")
print 'TEMPLATE:',t.substitute(val) s = """
Variable : %(var)s
Escape : %%
Variable in text : %(var)siable
"""
print "INTERPOLATION:", s % val

  执行结果:

  TEMPLATE:
  Variable : Victory
  Escape   : Victory
  Variable in text : Victoryiable

  INTERPOLATION:
  Variable : Victory
  Escape   : %
  Variable in text : Victoryiable

  在这两种情况下,触发器字符($ or %) 都要写连词来完成转义,其中此处需要注意的是使用% 进行传递字典参数时,方式是%(var)s 后面的s必不可少不然会报异常

  模板与标准字符串拼接有一个重要的区别,即模板不考虑参数类型都是字符串,不会出现控制几位有效情况出现。

  2、使用safe_substitute() 方法,可以避免未能提供模板所需全部参数值时产生的异常

 import string
val = {'var':'Victory'}
t = string.Template("$var is here but $missing is not provided")
try:
print 'substiture() :',t.substitute(val)
except KeyError,err:
print "ERROR:", str(err) print 'safe_substitute():' , t.safe_substitute(val)

  执行结果:

  substiture()          : ERROR: 'missing'
  safe_substitute(): Victory is here but $missing is not provided

  由于val中没有missing的值,所以会把出一个异常,但是在safe_substitute()中不会抛出这个错误,它会捕获这个异常,并在文本中保留变量表达式

三、高级模板

  可以修改string.Tempate默认语法,调整正则表达式,最简单的是修改delimiter 和 idpattern

  

 import string
template_text = """
Delimiter :%%
Replaced : %with_underscore
Ignored : %notunderscored
"""
d = { 'with_underscore' :'repaced',
'notunderscored':'not replaced'
}
class MyTemplate(string.Template):
delimiter = '%'
idpattern = '[a-z]+_[a-z]+' t = MyTemplate(template_text)
print 'Modified ID pattern:'
print t.safe_substitute(d)

  执行结果:  

  Modified ID pattern:

   Delimiter :%
      Replaced : repaced
      Ignored : %notunderscored

  在以上的例子中,我们更改了替换规则,定界符从$变成了%,变量名必须包含一个_,所以Ignored中没有获得值。要完成更复杂的修改,可以覆盖pattern属性。

  定义一个全新的正则表达式,所提供的模式必须包含四个命名组,分别对应转义定界符、命名变量、用大括号括住的正则表达式,已经不合法的定界符模式。

 import string
t = string.Template('$var')
print t.pattern.pattern

  执行结果:分别代表上面的四种命名组

      \$(?:
      (?P<escaped>\$) |   # Escape sequence of two delimiters
      (?P<named>[_a-z][_a-z0-9]*)      |   # delimiter and a Python identifier
      {(?P<braced>[_a-z][_a-z0-9]*)}   |   # delimiter and a braced identifier
      (?P<invalid>)              # Other ill-formed delimiter exprs
    )
   下面,我们就拉定义一个新的模式

 import string
import re class MyTemplate(string.Template):
delimiter = '{{'
pattern = r'''
\{\{(?:
(?P<escaped>\{\{)|
(?P<named>[_a-z][_a-z0-9]*)\}\}|
(?P<braced>[_a-z][_a-z0-9]*)\}\}|
(?P<invalid>)
)
'''
t = MyTemplate('''
{{{{
{{var}}
''')
print 'MATCHES:',t.pattern.findall(t.template)
print 'SUBSTITUTED: ',t.safe_substitute(var = 'relacement')

  执行结果:

  MATCHES: [('{{', '', '', ''), ('', 'var', '', '')]
  SUBSTITUTED:  
      {{
      relacement

  注意named 和 braced 模式必须单独提供,尽管看上去是一样的。

每日一“酷”之string的更多相关文章

  1. 每日一“酷”之array

    array--国定类型数据序列 array模块定义一个序列数据结构,看起来和list非常相似,只不过所有成员都必须是相同的基本类型. 1.初始化 array实例化时可以提高一个参数来描述允许哪个种数据 ...

  2. C++工程师养成 每日一题(string使用)

    题目: 题目来源牛客网:https://www.nowcoder.com/practice/f0db4c36573d459cae44ac90b90c6212?tpId 输入两个字符串,从第一字符串中删 ...

  3. 每日一“酷”之Cookie

    Cookie---Http Cookie 作用:Cookie模块定义一些类来解析和创建HTTP cookie首部 Cookie模块为大多数符合RFC 2109的cookie实现一个解析器.这个实现没有 ...

  4. 每日一“酷”之Queue

    Queue—线程安全的FIFO实现 作用:提供一个线程安全的FIFO实现 Queue模块提供了一个适用于多线程编程的先进先出(first-in,first-out)数据结构,可以用来在生产者和消费者线 ...

  5. 每日一“酷”之pprint

    pprint – 美观打印 作用:美观打印数据结构 pprint 包含一个“美观打印机”,用于生成数据结构的一个美观视图.格式化工具会生成数据结构的一些表示,不仅可以由解释器正确地解析,而且便于人类阅 ...

  6. 每日一“酷”之copy

    Copy – 复制对象 作用:提供一些函数,可以使用浅副本或深副本语义复制对象. copy模块包括两个函数copy()和deepcopy(),用于复制现有的对象 1.  浅副本 copy()创建的浅副 ...

  7. 每日一“酷”之heapq

    作用:heapq模块实现一个适用于Python列表的最小堆排序算法 堆(heap)是一个属性数据结构,其中子节点与父节点是一种有序关系.二叉堆是一种特殊的堆,二叉堆是完全二元树(二叉树)或者是近似完全 ...

  8. 每日一“酷”之bisect

    作用:维护有序列表,而不必在每次想列表增加一个元素时调用sort排序 bisect 模块实现了一个算法用于向列表中插入元素,同时仍保持列表有序.有些情况下,这比反复对一个了表序列更高效,另外也比构建一 ...

  9. 每日一“酷”之difflib

    介绍:difflib 比较序列.该模块包含一些用来计算和处理序列直接差异的工具.她对于比较文本尤其用,其中包含的函数可以使用多种常用差异格式生成报告. 测试数据(splitlines()按行划分为序列 ...

随机推荐

  1. asp.net在word页眉插入条形码

    条形码控件需要引用MSBCODE9.OCX组件.该组件的默认位置是C:\Program Files\Microsoft Office\Office12\2052\MSBCODE9.OCX using  ...

  2. VMware系统运维(四)SQL Server 2008 R2 新建数据库与ODBC数据

    1.新建数据库,右击"新建数据库-." 2.设置数据库名,初始数据库大小,如果要配置数据库优化,可以考虑初始大小与日志大小,点击添加安装完成,即完成数据库新建. 3.ODBC数据源 ...

  3. oracle数据操纵语言(DML)data manipulation language(续集)

    SQL查询语句(SELECT)进阶分组函数(Group Functions):对多行进行操作,并为每一组给出一个结果. AVG([DISTINCT|ALL] expression) 平均值COUNT ...

  4. 怒刷DP之 HDU 1257

    最少拦截系统 Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Submit Statu ...

  5. 转: ffmpeg 的deom列表

    http://blog.csdn.net/leixiaohua1020/article/details/47072861

  6. 十九、android中判断sim卡状态和读取联系人资料的方法

    在写程序中,有时候可能需要获取sim卡中的一些联系人资料.在获取sim卡联系人前,我们一般会先判断sim卡状态,找到sim卡后再获取它的资料,如下代码我们可以读取sim卡中的联系人的一些信息. Pho ...

  7. Part 11 string functions in sql server

    Built in string functions in sql server 2008 LEFT, RIGHT, CHARINDEX and SUBSTRING functions in sql s ...

  8. js 数组的length(javascript教程四)

    这是一个简单的函数,就是利用length来判断数组再遍历数组了. <script language="javascript" type="text/javascri ...

  9. redistribute_prefix

    使用分发列表和前缀列表控制路由 拓扑如下 将基本环境(ip和路由协议)配置好,所得到的各个路由表如下 R1: R2: R3: EIGRP和OSPF间的双向重分发 1.      在R2上做重分发 2. ...

  10. IE8 textarea 滚动条定位不准解决方法

    工作中遇到一个bug: IE8 下textarea 如果带滚动条(height:100px;overflow:scroll-y;),内容高度超过可视区域之后,输入文字,滚动条位置会乱跳. 开始以为是j ...