毎日1“クール”のstring

14392 ワード

紹介:stringモジュールは最も古いPythonバージョンに遡ることができます.現在strとunicodeオブジェクトに移植される多くの方法はpython 3.0では完全に除去されます.stringモジュールには、stringオブジェクトとunicodeオブジェクトを処理するのに役立つ定数と疲れがたくさんあります.
一、関数
1、capwords()の役割は、1つの文字列のすべての単語の頭文字を大文字にすることである.
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 onething,today is difficult,tomorrow is more difficult,but the day after tomorrow is beautifulWe Believe One Thing,today Is Difficult,tomorrow Is More Difficult,but The Day After Tomorrow Is BeautifulWe believe thing,Today is difficult,Tomorrow is more difficult w is beautiful
Capwords(s,seq)では2つのパラメータを渡すことができ、1つ目は処理が必要な文字列である.2つ目は、どのような条件で分割するか(デフォルトのスペース).
この関数の動作原理は死んでおり,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 beautifulW3 63113v3 0n3 7h1n6,70d4y 15 d1ff1cu17,70m0220w 15 m023 d1ff1cu17,6u7 7h3 d4y 4f732 70m0220w 15 634u71fu1
maketrans(fromstr,tostr)では、2つのパラメータを渡す必要があります.1つ目は置換する文字で、2つ目はなぜ文字に置換するかです.2つの文字列は同じ長さでなければなりません.そうしないと、異常が報告されます.
にばん
主に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プロパティを上書きします.
新しい正規表現を定義します.提供されるモードは、エスケープデリミタ、ネーミング変数、カッコで囲まれた正規表現に対応する4つのネーミンググループを含む必要があります.すでに合法的ではないデリミタモードです.
1 import string

2 t = string.Template('$var')

3 print t.pattern.pattern

実行結果:上の4つのネーミンググループをそれぞれ表します.
     \$(?:      (?P\$) |   # Escape sequence of two delimiters      (?P[_a-z][_a-z0-9]*)      |   # delimiter and a Python identifier      {(?P[_a-z][_a-z0-9]*)}   |   # delimiter and a braced identifier      (?P)#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モードは別々に提供されなければならないことに注意してください.