每日一“酷”之string

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

一、 函数

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

1 import string
2 s = 'We believe one thing,today is difficult,tomorrow is more difficult,but the day after tomorrow is beautiful'
3 print s 
4 print string.capwords(s)
5 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()方法将一组字符串修改为另一组字符

1 import string
2 s = 'We believe one thing,today is difficult,tomorrow is more difficult,but the day after tomorrow is beautiful'
3 leet = string.maketrans('abegiloprstz', '463611092572')
4 print s 
5 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、下面做一个模板和使用%操作符的比较

 1 import string 
 2 val = {'var':'Victory'}
 3 t = string.Template("""
 4 Variable : $var
 5 Escape   : $var
 6 Variable in text : ${var}iable 
 7 """)
 8 print  'TEMPLATE:',t.substitute(val)
 9 
10 s = """
11 Variable : %(var)s
12 Escape   : %%
13 Variable in text : %(var)siable 
14 """
15 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() 方法,可以避免未能提供模板所需全部参数值时产生的异常

1 import string 
2 val = {'var':'Victory'}
3 t = string.Template("$var is here but $missing is not provided")
4 try:
5     print 'substiture()          :',t.substitute(val)
6 except KeyError,err:
7     print "ERROR:", str(err)
8 
9 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

  

 1 import string
 2 template_text = """
 3     Delimiter :%%
 4     Replaced : %with_underscore
 5     Ignored : %notunderscored
 6 """
 7 d = {   'with_underscore' :'repaced',
 8         'notunderscored':'not replaced' 
 9      } 
10 class MyTemplate(string.Template):
11     delimiter = '%'
12     idpattern = '[a-z]+_[a-z]+'
13 
14 t = MyTemplate(template_text)
15 print 'Modified ID pattern:'
16 print t.safe_substitute(d)

  执行结果:  

  Modified ID pattern:

      Delimiter :%
      Replaced : repaced
      Ignored : %notunderscored

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

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

1 import string
2 t = string.Template('$var')
3 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
    )
   下面,我们就拉定义一个新的模式

 1 import string
 2 import re
 3 
 4 class MyTemplate(string.Template):
 5     delimiter = '{{'
 6     pattern = r'''
 7                     {{(?:
 8                       (?P<escaped>{{)|   
 9                       (?P<named>[_a-z][_a-z0-9]*)}}|    
10                       (?P<braced>[_a-z][_a-z0-9]*)}}|
11                       (?P<invalid>)        
12                     )
13                 '''
14 t = MyTemplate('''
15     {{{{
16     {{var}}
17 ''')
18 print 'MATCHES:',t.pattern.findall(t.template)
19 print 'SUBSTITUTED: ',t.safe_substitute(var = 'relacement')

  执行结果:

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

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

原文地址:https://www.cnblogs.com/victroy/p/4012397.html