#!/usr/bin/env python #-*- coding:UTF-8 -*- ##################################################### # Author: sunfx [email protected] # Last modified: 2014/11/11 # Filename: string.py # Q Q 群: 236147801 ##################################################### import re import string str = ‘I love python‘ #1.生成20个字符长度 print str.center(20) #2.字符左对齐 print str.ljust(20) #3.字符右对齐 print str.rjust(20) #4.str右对齐,左边填充0 print str.zfill(20) #5.所有字符大写 print str.upper() #6.所有字符转小写 print str.lower() #7.所有单词的首字母大写 s = ‘Thi quick brown fox jumped over the lazy dog.‘ print s print string.capwords(s) #8.大小写对换 print str.swapcase() #9.已分割符为标记,首字符大写,其余小写 print str.title() #10.模版转换 字符替换 比replace更有效率 leet = string.maketrans(‘abegiloprstz‘,‘463611092572‘) s = ‘Thi quick brown fox jumped over the lazy dog.‘ print s print s.translate(leet) str = ‘0123‘ #11.是否全部是字母和数字,并至少有一个字符 print str.isalnum() #12.是否全部是数字,并至少有一个字符 print str.isdigit() #13.判断是否全是字母,并且至少一个字符 print str.isalpha() #14.判断是否是小写,当全是小写和数字一起时候,也判断为True print str.islower() #15.判断是否是空白字符,并且至少有一个字符 print str.isspace() #16.判断字符是否以str开头 print str.startswith(‘str‘) #17.判读字符是否以str结尾 print str.endswith(‘str‘) str = ‘string 1EAMD‘ #18.查找字符,没有返回-1,有责返回查到第一个匹配的索引 print str.find(‘a‘) #19.查找字符,没有返回-1,有责返回查到最后一次匹配的索引 print str.rfind(‘a‘) #20.查找字符,如果没有报错,有责返回查到第一个匹配的索引 print str.index(‘s‘) #21.查找字符,没有报错,有责返回查到最后一次匹配的索引 print str.rindex(‘s‘) #22.查找字符串在字符中出现的次数 print str.count(‘s‘) #23.替换匹配的字符 print str.replace(‘s‘,‘A‘) #24.删除字符串首尾匹配的字符,通用用于删除回车符 print str.strip(‘n‘) #25.删除左边匹配的字符 print str.lstrip(‘n‘) #26.删除右边匹配的字符 print str.rstrip(‘n‘) #27.把制表符转为空格 str = ‘ tab‘ print str.expandtabs() str = ‘我在学习‘ #28.解码过程,将utf-8解码为unicode print str.decode(‘utf-8‘) #29.编码过程,将unicode编码为gbk print str.decode(‘utf-8‘).encode(‘gbk‘) #30.讲unicode编码为utf-8 print str.decode(‘utf-8‘).encode(‘utf-8‘) #31.字符分割 str = ‘Learn string‘ print ‘-‘.join(str) #32.以什么为分割 print str.split(‘ ‘) #33.模版Template values = {‘var‘:‘foo‘} t = string.Template(""" Variale : $var Escape : $$ Variable in text: ${var}iable """) print ‘TEMPLATE:‘,t.substitute(values) s = """ Variale : %(var)s Escape : %% Variable in text: %(var)siable """ print ‘INTERPOLATION:‘, s % values #34.Template 异常处理 t = string.Template("$var is here but $missing is not provided") try: print ‘substitute() :‘,t.substitute(values) except KeyError, err: print ‘ERROR:‘,str(err) print ‘safe_substitute():‘,t.safe_substitute(values) #36.高级模版 template_text = ‘‘‘ Delimiter : %% Replaced : %with_underscore Ignored : %notundersocred ‘‘‘ #37.可以自定义Templace 转换规则 d = { ‘with_underscore‘:‘replaced‘, ‘notundersocred‘:‘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) #38.自定义更复杂的规则 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 #python分隔符的标识(也就是变量) {(?P<braced>[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier #分隔符和一个支撑的标识 (?P<invalid>) # Other ill-formed delimiter exprs #无效的 ) ‘‘‘ 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 t.template #查看template的值 print ‘MATCHES:‘,t.pattern.findall(t.template) #查看正则匹配到的字符 print ‘SUBSTIITUTED:‘,t.safe_substitute(var=‘replacement‘) #使用替换 print MyTemplate.delimiter #查看mytemplate转义符 print string.Template.delimiter #查看string转义符 #http://legacy.python.org/dev/peps/pep-0292/ #格式化段落 #39.填充段落 左对齐,第一行缩进,行中空格继续保留 import textwrap sample_text = ‘‘‘ The textwrap modulde can be used to format text for output in situations where pretty-parinting is desired. It offers programmatic functionality similar to the paragraph wrapping or filling features found in myany text editors. ‘‘‘ print ‘No dedent:\n‘ print textwrap.fill(sample_text,width=50) #40.去除现有缩进(去除行中所有的空格) dedemted_text = textwrap.dedent(sample_text) print dedemted_text #41.结合fill和dedent 指定输出文字的宽度 dedemted_text = textwrap.dedent(sample_text).strip() print dedemted_text for width in [45,70]: print ‘%d Columns:\n‘ % width print textwrap.fill(dedemted_text,width=width) print #42.悬挂缩进 print textwrap.fill(dedemted_text, initial_indent=‘‘, #定义文本第一行缩进的长度 subsequent_indent=‘ ‘ * 4, #定义其他行的缩进 width=50 #定义文本长度,默认75 )
时间: 2024-10-25 19:47:58