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总结 - 第二章:字符串和文本
第二章:字符串和文本 几乎所有有用的程序都会涉及到某些文本处理,不管是解析数据还是产生输出. 这一章将重点关注文本的操作处理,比如提取字符串,搜索,替换以及解析等. 大部分的问题都能简单的调用字符串的 ...
随机推荐
- mysql 杀掉(kill) lock进程脚本
杀掉lock进程最快的方法是重启mysql,像你这种情况,1000多sql锁住了,最好是重启如果不允许重启,我提供一个shell脚本,生成 kill id命令杀掉lock线程,如下:--------- ...
- BZOJ 1012 线段树||单调队列
非常裸的线段树 || 单调队列: 假设一个节点在队列中既没有时间优势(早点入队)也没有值优势(值更大),那么显然不管在如何的情况下都不会被选为最大值. 既然它仅仅在末尾选.那么自然能够满足以上的条件 ...
- Shader编程教程
2010-05-13 11:37:14| 分类: DirectX 3D学习|举报|字号 订阅 Shader编程教程1-环境光照 您好,欢迎来到XNA Shader教程1.我的名字叫Petri ...
- IP地址加时间戳加3位随机数
工作中经常用到时间戳加上3位随机数获得唯一流水号,下面是代码~ package com.pb.viewer.filename; import java.text.SimpleDateFormat; i ...
- oracle中把函数的执行权限赋个某个用户
赋权:grant execute on function1 to ucr_dtb1;收回执行权限:revoke execute on function1 from ucr_dtb1; 在ucr_dtb ...
- MSP430G2553电子时钟实验
用msp430g2553控制1602液晶显示时间,并能够通过按键设置时间.我做了正计时和倒计时两种模式 /*********************************************** ...
- Openstack(Kilo)安装系列之环境准备(一)
本文采用VMware虚拟环境,使用CentOS 7.1作为openstack的基础环境. 一.基础平台 1.一台装有VMware的windows系统(可联网) 2.CentOS 7.1 64bit镜像 ...
- ios -仿微信有多级网页时,显示返回跟关闭按钮
@property (nonatomic, copy) NSString * url; @interface WebViewController ()<UIWebViewDelegate,UIG ...
- web安全之SQL注入---第五章 如何预防SQL注入 ?
5-1严格检查输入变量的类型和格式总结:其实就是做一些判断正则表达式:验证密码:/^[a-zA-Z]{6,}$/5-1严格检查输入变量的类型和格式总结:其实就是做一些判断正则表达式:验证密码:/^[a ...
- 圆环自带动画进度条ColorfulRingProgressView
这是项目中遇到了,我也是借鉴大神的, 下载地址:https://github.com/oooohuhu/ColorfulRingProgressView 我把它导入了github中了,里面有详细的使用 ...