python cookbook 字符串和文本
使用多个界定符分隔字符串
import re
line = 'asdf fjdk; afed, fjek,asdf, foo'
print(re.split(r'[;,\s]\s*', line))
print(re.split(r'(;|,|\s)\s*', line)) #加括号表示捕获分组,这样匹配的结果也显示在列表中
匹配开头或结尾
url = 'http://www.python.org'
print(url.startswith(('http', 'https', 'ftp'))) # 如果匹配多个一定是元组,list和set必须先调用tuple()转成元祖
import re
print(re.match('http:|https:|ftp:', url)) #正则也可以
使用Shell中的通配符匹配
from fnmatch import fnmatch, fnmatchcase
print('foo.txt', '*.txt')
print('foo.txt', '?oo.txt')
print('Dat45', 'Dat[0-9]*')
names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
print([name for name in names if fnmatch(name, 'Dat*.csv')])
忽略大小写匹配和替换
import re
text = 'UPPER PYTHON, lower python, Mixed Python'
print(re.findall('python', text, re.IGNORECASE))
print(re.findall('python', text))
print(re.sub('python', 'java', text, count=100, flags=re.IGNORECASE))
贪婪和非贪婪匹配
(.*)匹配任意字符,贪婪匹配。(.*?)非贪婪匹配
import re
str_pat = re.compile(r'\"(.*)\"')
text = 'Computer says "no." Phone says "yes."'
print(str_pat.findall(text))
str_pat = re . compile(r'\"(.*?)\"')
print(str_pat.findall(text))
多行匹配
import re
comment = re.compile(r'/\*(.*?)\*/')
text1 = '/* this is a comment */'
text2 = '''/* this is a
multiline comment */
'''
print(comment.findall(text1))
print(comment.findall(text2)) #在这个模式中,(?:.|\n)指定了一个非捕获组 (也就是它定义了一个仅仅用来做匹配,而不能通过单独捕获或者编号的组)。
comment = re.compile(r'/\*((?:.|\n)*?)\*/')
print(comment.findall(text2))
#re.DOTALL 它可以让正则表达式中的点(.)匹配包括换行符在内的任意字符。
comment = re.compile(r'/\*(.*?)\*/', re.DOTALL)
print(comment.findall(text2))
删除字符串中不需要的字符
import re
s = ' hello world \n '
print(s.strip())
print(s.strip(' \n'))
print(s.replace(" ", ""))
print(re.sub('\s+', ' ', s))
输出:
hello world
hello world
helloworld hello world
字符串对齐
text = 'Hello World'
print(text.rjust(20, "*"))
print(text.center(20,'*'))
#python3
print(format(text, '>20'))
print(format(text, '<20'))
print(format(text, '^20'))
print(format(text, '*>20'))
print(format(text, '=<20'))
print(format(text, '*^20'))
print('{:>10s} {:>10s}'.format('hello', 'world'))
x = 1.2345
print(format(x, '>10'))
print(format(x, '^10.2f'))
#python2
print('%-20s' % text)
print('%20s' % text)
字符串拼接
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
print(' '.join(parts)) # 最快的方法
print('hello' + ' ' + 'world') # 如果只是简单的拼接几个字符串,这样就可以了
print('hello' ' world') # 这样也ok
s = ''
for p in parts: # never do this
s += p
parts = ['now', 'is', 10, ':', '45']
print(' '.join(str(d) for d in parts)) # 用生成器来连接非str
a, b, c = ['f', 'z', 'k']
print (a + ':' + b + ':' + c) # Ugly
print (':'.join([a, b, c])) # Still ugly
print (a, b, c, sep=':') # Better
def sample(): #如果构建大量的小字符串,考虑用生成器的方式
yield 'Is'
yield 'Chicago'
yield 'Not'
yield 'Chicago?'
print(' '.join(sample()))
字符串插入变量
class Info(object):
def __init__(self, name, n):
self.name = name
self.n = n
s = '{name} has {n} messages.'
name = 'fzk'
n = 10
print(s.format(name=name, n=n))
print(s.format_map(vars()))
print(s.format_map(vars(Info(name, n))))
#如果变量缺失,会印发报错。可以用下面的方法
class safesub (dict):
""" 防止key 找不到"""
def __missing__ (self, key):
return '{' + key + '}'
del n
print(s.format_map(safesub(vars())))
python cookbook 字符串和文本的更多相关文章
- 《Python CookBook2》 第一章 文本 - 过滤字符串中不属于指定集合的字符 && 检查一个字符串是文本还是二进制
过滤字符串中不属于指定集合的字符 任务: 给定一个需要保留的字符串的集合,构建一个过滤函数,并可将其应用于任何字符串s,函数返回一个s的拷贝,该拷贝只包含指定字符集合中的元素. 解决方案: impor ...
- Python:字符串
一.序列的概念 序列是容器类型,顾名思义,可以想象,“成员”们站成了有序的队列,我们从0开始进行对每个成员进行标记,0,1,2,3,...,这样,便可以通过下标访问序列的一个或几个成员,就像C语言中的 ...
- python cookbook学习1
python cookbook学习笔记 第一章 文本(1) 1.1每次处理一个字符(即每次处理一个字符的方式处理字符串) print list('theString') #方法一,转列表 结果:['t ...
- python书籍推荐:Python Cookbook第三版中文
所属网站分类: 资源下载 > python电子书 作者:熊猫烧香 链接:http://www.pythonheidong.com/blog/article/44/ 来源:python黑洞网 内容 ...
- Python Cookbook(第3版) 中文版 pdf完整版|网盘下载内附提取码
Python Cookbook(第3版)中文版介绍了Python应用在各个领域中的一些使用技巧和方法,其主题涵盖了数据结构和算法,字符串和文本,数字.日期和时间,迭代器和生成器,文件和I/O,数据编码 ...
- 【NLP】Python NLTK处理原始文本
Python NLTK 处理原始文本 作者:白宁超 2016年11月8日22:45:44 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集的大量公开 ...
- python基础——字符串和编码
python基础——字符串和编码 字符串也是一种数据类型,但是,字符串比较特殊的是还有一个编码问题. 因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.最早的计算机在设计时采用 ...
- python之字符串
字符串与文本操作 字符串: Python 2和Python 3最大的差别就在于字符串 Python 2中字符串是byte的有序序列 Python 3中字符串是unicode的有序序列 字符串是不可变的 ...
- Python3-Cookbook总结 - 第二章:字符串和文本
第二章:字符串和文本 几乎所有有用的程序都会涉及到某些文本处理,不管是解析数据还是产生输出. 这一章将重点关注文本的操作处理,比如提取字符串,搜索,替换以及解析等. 大部分的问题都能简单的调用字符串的 ...
随机推荐
- (四)Thymeleaf标准表达式之——[3->6] 操作符(文本、算术、布尔、比较及相等)
2.3 文本操作符 模板名称:text.html 连接符: + 可以是任意字符和表达式等 文本替换符:| 不能表达出条件表达式(官网:只能是变量表达式) e.g. 1.<span th ...
- html5 的a标签是可以拨电话的,通过其Href属性来实现
<a href="tel:18700000000">点击给我打电话吧!</a> 注: 1.<a href="tel:18750000000& ...
- .Net、C# 汉字转拼音,简体繁体转换方法
Visual Studio International Pack 包含一组类库,该类库扩展了.NET Framework对全球化软件开发的支持.使用该类库提供的类,.NET 开发人员可以更方便的创建支 ...
- RAII手法封装相互排斥锁
CriticalSectionWrapper是一个接口类 class CriticalSectionWrapper { public: // Factory method, constructor d ...
- php SSL certificate problem: unable to get local issuer certificate
加上 curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE); 就可以了 百度语音的demo: <?php header("Content-type ...
- 解密和解压浏览器上加密的js文件
F12 -> 进入Sources -> 找到任意一个加密的js文件,如图 点击最下方的 {} 即可解压
- linux的用户、群组
1. 用户及passwd文件 1) 掌握/etc/passwd文件的功能:存储所有用户的相关信息,该文件也被称为用户信息数据库(Database). 2) /etc/pa ...
- win7上python+theano+keras安装
https://blog.csdn.net/yongjiankuang/article/details/50485610 其实过程很简单,首先说一下安装条件: 1.win7 (32和64都可以,下载安 ...
- (C#)为应用程式设定运行权限(System.Security类下的GenericIdentity,GenericPrincipal,PrincipalPermission)
最近看书<编写高质量代码改善C#程序的157个建议>,知识点备忘: System.Security.Principal.GenericIdentity==>表示一般用户 System ...
- Solr In Action 中文版 第一章(四、五)
1.1 功能概览1. 4 最后,让我们再依照以下的分类.高速的过一下Solr的主要功能: ·用户体验 ·数据建模 ·Solr 4的新功能 在本书中.为你的用户提供良好的搜索体验 ...