Python3 CookBook学习笔记 -- 字符串和文本

1. 字符串开头或结尾匹配

需要通过指定的文本模式去检查字符串的开头或者结尾,比如文件名后缀,URL Scheme等等。

我们可以使用字符串的endswithstartswith

>>> url = 'http://www.python.org'
>>>
>>> url
'http://www.python.org'
>>> url.endswith('org')
True
>>> url.startswith('http://')
True

如果想检查多种类型匹配,那么我们可以使用元组进行包装

>>> import os
>>> filenames = os.listdir('.')
>>> filenames
[ 'Makefile', 'foo.c', 'bar.py', 'spam.c', 'spam.h' ]
>>> [name for name in filenames if name.endswith(('.c', '.h')) ]
['foo.c', 'spam.c', 'spam.h']
>>> any(name.endswith('.py') for name in filenames)
True
>>>

2. 字符串对齐

对于基本的字符串对齐操作,可以使用字符串的 ljust() , rjust()center() 方法。比如:

>>> text = 'Hello World'
>>> text.ljust(20)
'Hello World         '
>>> text.rjust(20)
'         Hello World'
>>> text.center(20)
'    Hello World     '
>>>

意思为:共准备20个长度,减去字符串本身的长度,剩余用空格填充。

函数 format() 同样可以用来很容易的对齐字符串。 你要做的就是使用 < , > 或者 ^ 字符后面紧跟一个指定的宽度。比如:

  • < 等同于 ljust(),字符串居左。

  • > 等同于 rjust(),字符串居右。

  • ^等同于 center(),字符串居中。

>>> format(text, '>20')
'         Hello World'
>>> 
>>> format(text, '<20')
'Hello World         '
>>> 
>>> format(text, '^20')
'    Hello World     '

也可以使用其他填充物

>>> format(text, '-^20')
'----Hello World-----'

当然我可以也可是使用 格式化符号

>>> format(text, '=>20s')
'=========Hello World'

我们也可以同时格式化多个值

>>> '{:>10s} {:>10s}'.format('Hello', 'World')
'     Hello      World'

python3中,我们需要忘记 python2中的%s%d等等,请优先使用 format

3. 合并拼接字符串

如果你想要合并的字符串是在一个序列或者 iterable 中,那么最快的方式就是使用 join() 方法。

>>> parts = ['Is', 'Chicago', 'Not', 'Chicago?']
>>> ' '.join(parts)
'Is Chicago Not Chicago?'

请尽量不要使用 +来完成字符串拼接,因为加号连接会引起内存复制以及垃圾回收操作。以下代码应禁止:

s = ''
for p in parts:
    s += p

因为每一次执行+=操作的时候会创建一个新的字符串对象。 你最好是先收集所有的字符串片段然后再将它们连接起来。

第一反应应该是 生成器

>>> data = ['ACME', 50, 91.1]
>>> ','.join(str(d) for d in data)
'ACME,50,91.1'

字符串打印:

效率以及代码观赏性上,最后一个是最好的。

print(a + ':' + b + ':' + c)  
print(':'.join([a, b, c])) 
print(a, b, c, sep=':') 

4. 字符串中插入变量

方法1

>>> s = '{} has {} messages.'
>>> s.format('Guido', 37)
'Guido has 37 messages.'

方法2

>>> s = '{:^7} has {:^7} messages.'
>>> 
>>> s.format('Guido', 37)
' Guido  has   37    messages.'

方法2

>>> s = '{name} has {n} messages.'
>>> s.format(name='Guido', n=37)
'Guido has 37 messages.'

5. 以指定列宽格式化字符串

如果你想输出自动匹配终端大小的时候,你需要指定列宽进行格式化字符串

>>> import os
>>> os.get_terminal_size()
os.terminal_size(columns=181, lines=46)
>>> 
>>> s = "Look into my eyes, look into my eyes, the eyes, the eyes, \
... the eyes, not around the eyes, don't look around the eyes, \
... look into my eyes, you're under."
>>>  
>>> s
"Look into my eyes, look into my eyes, the eyes, the eyes, the eyes, not around the eyes, don't look around the eyes, look into my eyes, you're under."
>>> import textwrap
>>> 
>>> print(textwrap.fill(s, 70))
Look into my eyes, look into my eyes, the eyes, the eyes, the eyes,
not around the eyes, don't look around the eyes, look into my eyes,
you're under.
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容