python3-cookbook笔记:第二章 字符串和文本
python3-cookbook中每个小节以问题、解决方案和讨论三个部分探讨了Python3在某类问题中的最优解决方式,或者说是探讨Python3本身的数据结构、函数、类等特性在某类问题上如何更好地使用。这本书对于加深Python3的理解和提升Python编程能力的都有显著帮助,特别是对怎么提高Python程序的性能会有很好的帮助,如果有时间的话强烈建议看一下。
本文为学习笔记,文中的内容只是根据自己的工作需要和平时使用写了书中的部分内容,并且文中的示例代码大多直接贴的原文代码,当然,代码多数都在Python3.6的环境上都验证过了的。不同领域的编程关注点也会有所不同,有兴趣的可以去看全文。
python3-cookbook:https://python3-cookbook.readthedocs.io/zh_CN/latest/index.html
2.1 使用多个界定符分割字符串
一般字符串的分割用str.split足以胜任,但是在复杂的文本中查找分割字符串,正则表达式是无疑是首选的工具,re模块也有一个分割字符串的函数split,需要注意的是正则表达式中如果有括号分组的话,分组的结果也会在结果列表中。
>>> import re
>>> line = 'asdf fjdk; afed, fjek,asdf, foo'
>>> re.split(r'[;,\s]\s*', line)
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
>>> fields = re.split(r'(;|,|\s)\s*', line) # 分组的内容也会出现在结果里
>>> fields
['asdf', ' ', 'fjdk', ';', 'afed', ',', 'fjek', ',', 'asdf', ',', 'foo']
>>>
2.3 用Shell通配符匹配字符串
当字符串的匹配一般方法不能满足,但又不想用正则表达式那么复杂,可以考虑使用fnmatch.fnmatch或fnmatch.fnmatchcase,两者都可以使用Unix Shell中常用的通配符匹配字符串,区别在于前者使用的是操作系统的大小写敏感规则,后者则完全按照你写的内容去匹配。
>>> from fnmatch import fnmatch, fnmatchcase
>>> fnmatch('foo.txt', '*.txt')
True
>>> fnmatch('foo.txt', '?oo.txt')
True
>>> fnmatch('Dat45.csv', 'Dat[0-9]*')
True
>>>
2.13 字符串对齐
字符串对齐是字符串格式化的一部分,对于普通的左对齐,右对齐和居中对齐可以使用字符串的ljust、rjust和center方法,也可以使用内置的format函数和字符串的format方法,文中推荐使用format,因为后者在字符串的格式化功能上更加的丰富和强大。
字符串的对齐工作中似乎并不常用,但我遇到过一个使用场景,就是使用字符串表示的二进制数时,需要用0或1来将字符串补齐为8位或者16位的字符串,这时字符串的对齐功能就排上用场了。
>>> 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(text, '>20')
' Hello World'
>>> format(text, '<20')
'Hello World '
>>> format(text, '^20')
' Hello World '
>>> format(text, '=<20s')
'Hello World========='
>>> format(text, '*^20s')
'****Hello World*****'
>>> # 格式化数字
>>> x = 1.2345
>>> format(x, '^10.2f')
' 1.23 '
>>> # 字符串的format方法
>>> '{:>10s} {:>10s}'.format('Hello', 'World')
' Hello World'
2.16 以指定列宽格式化字符串
这个问题在打印信息或者在终端展示信息的时候可能会遇到,此时可以使用textwrap来指定输出列宽。
>>> import textwrap
>>> 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."
>>> 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.
>>> print(textwrap.fill(s, 40))
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.
>>> print(textwrap.fill(s, 40, initial_indent=' '))
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.
>>> print(textwrap.fill(s, 40, subsequent_indent=' '))
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.
>>>
2.17 在字符串中处理html和xml
在处理HTML或XML文本的时候,想要将如&entity;或&#code;替换为对应的文本,或者反过来操作,只需要使用对应解析器的工具函数即可,当然,如果你比较熟悉对应的解析器的话或许有更好的方法。
>>> import html
>>> s = 'Elements are written as "<tag>text</tag>".'
>>> print(s)
Elements are written as "<tag>text</tag>".
>>> print(html.escape(s))
Elements are written as "<tag>text</tag>".
>>> print(html.escape(s, quote=False))
Elements are written as "<tag>text</tag>".
>>>
>>> from html.parser import HTMLParser
>>> s = 'Spicy "Jalapeño".'
>>> p = HTMLParser()
>>> p.unescape(s)
'Spicy "Jalapeño".'
>>>
>>> from xml.sax.saxutils import unescape
>>> t = 'The prompt is >>>'
>>> unescape(t)
'The prompt is >>>'
>>>
2.18 字符串令牌解析
令牌化字符串可以使用正则表达式的命名捕获分组来进行,语法为“(?P<group_name>)”,这个问题在解析用户自定义的计算公式字符串时会很有用。
解决这个问题时,可以考虑使用模式对象的scanner方法,并打包到一个生成器中使用。
import re NAME = r'(?P<NAME>[a-zA-Z_][a-zA-Z_0-9]*)'
NUM = r'(?P<NUM>\d+)'
PLUS = r'(?P<PLUS>\+)'
TIMES = r'(?P<TIMES>\*)'
EQ = r'(?P<EQ>=)'
WS = r'(?P<WS>\s+)' master_pat = re.compile('|'.join([NAME, NUM, PLUS, TIMES, EQ, WS]))
scanner = master_pat.scanner('foo = 42')
for m in iter(scanner.match, None):
print(m.lastgroup, m.group())
NAME foo
WS
EQ =
WS
NUM 42
python3-cookbook笔记:第二章 字符串和文本的更多相关文章
- 《DOM Scripting》学习笔记-——第二章 js语法
<Dom Scripting>学习笔记 第二章 Javascript语法 本章内容: 1.语句. 2.变量和数组. 3.运算符. 4.条件语句和循环语句. 5.函数和对象. 语句(stat ...
- The Road to learn React书籍学习笔记(第二章)
The Road to learn React书籍学习笔记(第二章) 组件的内部状态 组件的内部状态也称为局部状态,允许保存.修改和删除在组件内部的属性,使用ES6类组件可以在构造函数中初始化组件的状 ...
- [HeadFrist-HTMLCSS学习笔记]第二章深入了解超文本:认识HTML中的“HT”
[HeadFrist-HTMLCSS学习笔记]第二章深入了解超文本:认识HTML中的"HT" 敲黑板!!! 创建HTML超链接 <a>链接文本(此处会有下划线,可以单击 ...
- Android群英传笔记——第二章:Android开发工具新接触
Android群英传笔记--第二章:Android开发工具新接触 其实这一章并没什么可讲的,前面的安装Android studio的我们可以直接跳过,如果有兴趣的,可以去看看Google主推-Andr ...
- 深入理解 C 指针阅读笔记 -- 第二章
Chapter2.h #ifndef __CHAPTER_2_ #define __CHAPTER_2_ /*<深入理解C指针>学习笔记 -- 第二章*/ /* 内存泄露的两种形式 1.忘 ...
- 《SQL CookBook 》笔记-第二章-查询结果排序
目录 第二章 查询结果排序 2.1 以指定顺序返回查询结果 2.2 依据子串排序 2.3 排序时对 Null 值的处理 2.4 依据条件逻辑动态调整排序项 第二章 shanzm 第二章 查询结果排序 ...
- c#高级编程第七版 学习笔记 第二章 核心c#
第二章 核心C# 本章内容: 声明变量 变量的初始化和作用域 C#的预定义数据类型 在c#程序中使用条件语句.循环和跳转语句执行流 枚举 名称空间 Main()方法 基本的命令行c#编译器选项 使用S ...
- 《图解HTTP》阅读笔记--第二章 简单的HTTP协议--第三章 HTTP报文信息
第二章.简单的HTTP协议HTTP协议:HTTP协议用于客户端(请求资源的一端)和服务器端(响应回复提供资源的一端)的通信,是一种无状态协议HTTP1.1默认TCP持久连接,管线化发送(并行发送多个 ...
- STL源码分析读书笔记--第二章--空间配置器(allocator)
声明:侯捷先生的STL源码剖析第二章个人感觉讲得蛮乱的,而且跟第三章有关,建议看完第三章再看第二章,网上有人上传了一篇读书笔记,觉得这个读书笔记的内容和编排还不错,我的这篇总结基本就延续了该读书笔记的 ...
随机推荐
- Mysql 5.7.18:主从复制,io优化
#目录 #挂盘#时间同步#master节点,进行如下操作: #下载安装 #初始化 #配置文件 #开机启动 #服务启动 #初始数据库#slave节点,进行如下操作: #下载安装 #初始化 #配置文件 # ...
- java中list的sort()功能如何使用?
排序时正序/倒序处理起来可能会混淆,可以用更简单的方法.可以使用java.util自带的比较器来做 Comparator.comparingInt(Integer::intValue).reverse ...
- 【python爬虫】windoes的爬虫中文乱码现象,通用转码解决
page = session.get(url="https://www.qidian.com/") page.encoding = page.apparent_encoding p ...
- Python LEGB (Local, Enclosing, Global, Build in) 规则
Local 一个函数定义了一个 local 作用域; PyFrameObject 中的 f_local 属性 Global 一个 module 定义了一个 global 作用域; PyFrameObj ...
- 从linux命令行分享文件:bashupload.com和transfer.sh
背景 传输文件是一个常见的需求,简单的做法是通过即时通讯工具,邮件,网盘完成. 但当分享或接收的一端为远程服务器,只有命令行可以操作时,一个能支持在命令行完成分享和下载的工具,就会省下不少麻烦. 下面 ...
- html input元素的所有type属性
<input /> 属性 type="text" 输入框的类型为文本 type="password" 输入框的类型为密码 type="ra ...
- Windows+Python+Selenium基础篇之1-环境搭建
1.所需工具包1.1Selenium for python1.2 Python 1.3 Notepad++或python IDE 2. 环境搭建2.1 下载和安装Pythonpython2. ...
- 大数相加-----杭电acm1002
#include<stdio.h> #include<string.h> int main() { ], ch2[]; ], num2[]; ; scanf("%d& ...
- vscode安装使用
1.新建文件:cmd+n2.设置默认浏览器: https://blog.csdn.net/zSY_snake/article/details/83449571 3.view in browser不支持 ...
- 快速筛出topK的快速选择算法和BFPRT优化
本文始发于个人公众号:TechFlow,原创不易,求个关注 在之前Python系列当中,我们介绍了heapq这个库的用法,它可以在\(O(nlogn)\)的时间里筛选出前K大或者前K小的元素.今天我们 ...