python cookbook 2字符串(3)

11从字符串中清除不想保留的字符python

能够用strip()清除字符串,默认清除空格,换行符,也能够提供须要清除的字符,还有lstrip()和rstrip().函数

>>> t = '-----hello====='
>>> t.strip()
'-----hello====='
>>> t.strip('-')
'hello====='
>>> t.strip('-=')
'hello'
须要注意一点,strip()没法清除字符串中间的字符,能够用replace或常量表达式
>>> s=' hello  world'
>>> s.replace('e','')
' hllo  world'
>>> import re
>>> re.sub('ll','',s)
' heo  world'

12清洗文本,仅针对python3(python2和3编码方式不一样)ui

>>> s = 'pýtĥöñ\fis\tawesome\r\n'
>>> s
'pýtĥöñ\x0cis\tawesome\r\n'
>>> remap = {ord('\t') : ' ',
... ord('\f') : ' ',#换页
... ord('\r') : None
... }
>>> a = s.translate(remap)
>>> a
'pýtĥöñ is awesome\n'
>>> import unicodedata
>>> b = unicodedata.normalize('NFD', a)#特殊字符所有采用两个字符组合的形式分解
>>> b
'pýtĥöñ is awesome\n'
>>> b.encode('ascii', 'ignore').decode('ascii')#忽略其中有异常的编码Unicode---ascii(过滤掉异常字符)-----Unicode
'python is awesome\n'
>>> b.encode('ascii', 'ignore')
b'python is awesome\n'

str.replace()速度更快一些,即便是屡次运行,也比translate()快一些
编码

13文本的排版code

>>> text = 'Hello World'
>>> text.ljust(20)
'Hello World         '
>>> text.rjust(20)
'         Hello World'
>>> text.center(20)
'    Hello World     '
还能够提供一些填充符
>>> text.rjust(20,'=')
'=========Hello World'
>>> text.center(20,'*')
'****Hello World*****'
format也能够用于简单排版,<^>表明左中右
>>> format(text, '>20')
'         Hello World'
>>> format(text, '<20')
'Hello World         '
>>> format(text, '^20')
'    Hello World     '
也能够指定填充符
>>> format(text, '=>20s')
'=========Hello World'
>>> format(text, '*^20s')
'****Hello World*****'
format还能够按指定格式输出多个字符和指定小数位数
>>> '{:>10s} {:>10s}'.format('Hello', 'World')
'     Hello      World'
>>> x = 1.2345
>>> format(x, '^10.2f')
'   1.23   '
一些老代码中还可能见到以下形式,不推荐使用
>>> '%-20s' % text
'Hello World         '
>>> '%20s' % text
'         Hello World'

14组合链接字符串orm

join能够拼接list
>>> parts = ['Is', 'Chicago', 'Not', 'Chicago?']
>>> ' '.join(parts)
'Is Chicago Not Chicago?'
>>> a = 'Is Chicago'
>>> b = 'Not Chicago?'
也能够用+拼接,注意+拼接不是最有效,每次拼接都至关于建立了一个新的对象,推荐用extend和join
>>> a + ' ' + b
'Is Chicago Not Chicago?'
也能够采用没有+的拼接
>>> a = 'Hello' 'World'
>>> a
'HelloWorld'
#若是仅仅是为了打印,python3中提供了分隔符标志位
print(a, b, c, sep=':')
对于一些IO操做,须要慎重考虑,若是两个字符串很小,version1比较合适,因为一些内在的IO系统调用的消耗
# Version 1 
f.write(chunk1 + chunk2)
# Version 2 
f.write(chunk1)
f.write(chunk2)
可是若是字符串较大,version2更有效,避免建立临时str变量和拷贝的内存消耗
也能够考虑用yield生成器,避免过多的内存消耗

15字符串中插入变量对象

>>> s = '{name} has {n} messages.'
>>> s.format(name='Guido', n=37)
'Guido has 37 messages.'
>>> name = 'Guido'
>>> n = 37
>>> s.format_map(vars())#***仅python3提供
#内建的 vars()函数接受类对象做为参数,返回类的__dict__属性的内容。
'Guido has 37 messages.'
#format和format_map在变量缺失时会抛出异常
能够在一个字典类中定义一个__missing__方法
>>> class safesub(dict):
...      def __missing__(self, key):
...          return '{' + key + '}'
... 
>>> del n
>>> s.format_map(safesub(vars()))
'Guido has {n} messages.'
相似的还可使用string.Template,可是更推荐使用format.
>>> import string
>>> s = string.Template('$name has $n messages.')
>>> s.substitute(vars())
'Guido has 37 messages.'
相关文章
相关标签/搜索