使用多个界定符分隔字符串

  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 字符串和文本的更多相关文章

  1. 《Python CookBook2》 第一章 文本 - 过滤字符串中不属于指定集合的字符 && 检查一个字符串是文本还是二进制

    过滤字符串中不属于指定集合的字符 任务: 给定一个需要保留的字符串的集合,构建一个过滤函数,并可将其应用于任何字符串s,函数返回一个s的拷贝,该拷贝只包含指定字符集合中的元素. 解决方案: impor ...

  2. Python:字符串

    一.序列的概念 序列是容器类型,顾名思义,可以想象,“成员”们站成了有序的队列,我们从0开始进行对每个成员进行标记,0,1,2,3,...,这样,便可以通过下标访问序列的一个或几个成员,就像C语言中的 ...

  3. python cookbook学习1

    python cookbook学习笔记 第一章 文本(1) 1.1每次处理一个字符(即每次处理一个字符的方式处理字符串) print list('theString') #方法一,转列表 结果:['t ...

  4. python书籍推荐:Python Cookbook第三版中文

    所属网站分类: 资源下载 > python电子书 作者:熊猫烧香 链接:http://www.pythonheidong.com/blog/article/44/ 来源:python黑洞网 内容 ...

  5. Python Cookbook(第3版) 中文版 pdf完整版|网盘下载内附提取码

    Python Cookbook(第3版)中文版介绍了Python应用在各个领域中的一些使用技巧和方法,其主题涵盖了数据结构和算法,字符串和文本,数字.日期和时间,迭代器和生成器,文件和I/O,数据编码 ...

  6. 【NLP】Python NLTK处理原始文本

    Python NLTK 处理原始文本 作者:白宁超 2016年11月8日22:45:44 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集的大量公开 ...

  7. python基础——字符串和编码

    python基础——字符串和编码 字符串也是一种数据类型,但是,字符串比较特殊的是还有一个编码问题. 因为计算机只能处理数字,如果要处理文本,就必须先把文本转换为数字才能处理.最早的计算机在设计时采用 ...

  8. python之字符串

    字符串与文本操作 字符串: Python 2和Python 3最大的差别就在于字符串 Python 2中字符串是byte的有序序列 Python 3中字符串是unicode的有序序列 字符串是不可变的 ...

  9. Python3-Cookbook总结 - 第二章:字符串和文本

    第二章:字符串和文本 几乎所有有用的程序都会涉及到某些文本处理,不管是解析数据还是产生输出. 这一章将重点关注文本的操作处理,比如提取字符串,搜索,替换以及解析等. 大部分的问题都能简单的调用字符串的 ...

随机推荐

  1. Java种八种常用排序算法

    1 直接插入排序 经常碰到这样一类排序问题:把新的数据插入到已经排好的数据列中. 将第一个数和第二个数排序,然后构成一个有序序列 将第三个数插入进去,构成一个新的有序序列. 对第四个数.第五个数……直 ...

  2. 基于多输出有序回归的年龄识别(CVPR_2016)

    作为学习记录,将所做PPT摘录如下: 网络结构: 网络结构描述: 网络工作流程: 损失函数计算: 亚洲人脸数据集: 参考代码:

  3. Atitit。Time base gc 垃圾 资源 收集的原理与设计

    Atitit.Time base gc 垃圾 资源 收集的原理与设计 1. MRC(MannulReference Counting手动 retain/release/autorelease语句1 2 ...

  4. JavaScript的split()

    JavaScript split() 方法 JavaScript String 对象 定义和用法 split() 方法用于把一个字符串分割成字符串数组. 语法 stringObject.split(s ...

  5. Unity3D性能优化之Draw Call Batching

    在屏幕上渲染物体,引擎需要发出一个绘制调用来访问图形API(iOS系统中为OpenGL ES).每个绘制调用需要进行大量的工作来访问图形API,从而导致了CPU方面显著的性能开销. Unity在运行时 ...

  6. linux 给用户修改权限

    #添加一个用户 useradd xiaoming #设置密码 passwd xiaoming 回程 //设置密码就行了 #把用户修改成root权限 vi /etc/passwd #找到xiaoming ...

  7. db2 error

    DB2 SQL Error: SQLCODE=-668, SQLSTATE=57016, SQLERRMC=7;MCD_BJ.MTL_CHANNEL_DEF, DRIVER=4.18.60 你的表处于 ...

  8. iOS图片无损拉伸

    一张图片如果放大的话一般情况下会失真,如果该图片是规则的,比如这个聊天气泡,可以用如下代码来设置 UIImage *rightImg = [UIImage imageNamed:@"Sen ...

  9. c# 当前不会命中断点 未载入该文档

    C#编码时.有时会遇到标题所说的问题,就是说这个文件和方法明明存在,可总是提示找不到方法.解决方法例如以下: 1.清理全部项目(或相关项目)生成 2.又一次加入全部项目(或相关项目)间的互相引用 3. ...

  10. LR测试HTTPS

    从浏览器里导出cer证书 保存好后, 下载openssl-1.0.1s安装好openssl之后,进入openssl目录: 输入openssl命令,即进入命令模式: 先将要转换的cer证书也放到open ...