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

  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. EFFECTIVE JAVA 第一天 静态工厂方法

    静态工厂方法:(这里指的是就是普通static方法),类可以通过静态工厂方法提供给它的客户端,而不是通过构造器.提供静态工厂方法而不是公有构造器,这样做有几大优势. 在类的实现中使用了API的类被称为 ...

  2. springMVC 【@response 返回对象自动变成json并且防止乱码】 & 【配置支持实体类中的@DateTimeFormat注解】

    在springmvc的配置文件中加上这一段即可 <bean class="org.springframework.web.servlet.mvc.annotation.Annotati ...

  3. PHP面试题及答案解析(8)—PHP综合应用题

    1.写出下列服务的用途和默认端口. ftp.ssh.http.telnet.https ftp:File Transfer Protocol,文件传输协议,是应用层的协议,它基于传输层,为用户服务,它 ...

  4. Selenium3.X 与 Javascript (Nodejs)

    传送门 # 官网网站 http://docs.seleniumhq.org/download/ # API DOC http://goo.gl/hohAut # 慕课网教程http://www.imo ...

  5. 标准库 - 输入输出处理(input and output facilities) lua

    标准库 - 输入输出处理(input and output facilities)责任编辑:cynthia作者:来自ITPUB论坛 2008-02-18 文本Tag: Lua [IT168 技术文档] ...

  6. UVA 10209

    10209 - Is This Integration ? #include <stdio.h> #include <math.h> /* */ //多次错误都是因为我将PI定 ...

  7. 如何落地全球最大 Kubernetes 生产集群

        鲍永成   京东基础架构部技术总监,   DevOps 标准核心编写专家   前言   JDOS 就是京东数据中心操作系统,随着数据中心规模不断的扩大,我们需要对数据中心做综合的考虑.所以一开 ...

  8. No breeds found in the signature, a signature update is recommended

    cobbler 2.6.11 遇到这个问题,需要 >> cobbler signature update >> and cobblerd restart 转自: https:/ ...

  9. 关于iphone自动播放音频和视频问题的解决办法

    大家都知道 做移动端 会遇到音频和视频无法自动播放问题(我也遇到了)于是想办法解决这个问题 我只是找到了在微信中解决的办法(如果谁有在别的浏览器有这个办法  请私聊我 )我是没有发现 document ...

  10. map 玩家上线

    map 玩家上线 else if(gs2ms_add_player == pkt.cmd) { PlayerChannel* pPC = new PlayerChannel(this); //加到地图 ...