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

  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. 远程链接mysql数据库

    mysql -P3306 -uroot -proot 显示最大连接数 show variables like '%max_connections%'; 设置最大链接数 ;//默认100--只对当前进程 ...

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

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

  3. Python基础--通用序列操作

    Python 继续 Python包含6种内建的序列,各自是:列表.元组.字符串.Unicode字符串.buffer对象和xrange对象.我们将逐步进行介绍. 今天主要介绍一下通用序列操作.放之四海而 ...

  4. hibernate单向多对一映射

    n21: 1.new 两个实体类,一个代表"多"的一端,一个代表"一"的一端. Customer类: public class Customer { priva ...

  5. 403/you don't have the permission to access on this server

    Localhost/index.php出现 错误403 you don't have the permission to access on this server 现在已经解决,特将方法与大家分享. ...

  6. 史上最全的CSS hack方式一览(转)

    做前端多年,虽然不是经常需要hack,但是我们经常会遇到各浏览器表现不一致的情况.基于此,某些情况我们会极不情愿的使用这个不太友好的方式来达到大家要求的页面表现.我个人是不太推荐使用hack的,要知道 ...

  7. linux下网卡bonding配置

    linux下网卡bonding配置   章节 bonding技术 centos7配置bonding centos6配置bonding 一.bonding技术 bonding(绑定)是一种linux系统 ...

  8. 【Mac + Pycharm】之实用东西以及配置东西

    一.新建.py文件时默认模板: 步骤:File => Preferences for New Projects => Editor => File and Code Template ...

  9. IE8 兼容 getElementsByClassName

    IE8以下版本没有getElementsByClassName这个方法,以下是兼容写法 function ieGetElementsByClassName() { if (!document.getE ...

  10. android 二维码制作,显示到UI,并保存SD卡,拿来就能用!!

    转载请注明出处:王亟亟的大牛之路 如今二维码已经渗透了我们的生活.各种扫码关注啊.扫码下载的,今天上一个依据输入内容生成二维码的功能. 包结构: 界面截图: 功能:输入网址–>生成图片–> ...