>>> import string
>>> s='hello rollen , how are you '
>>> string.capwords(s)
'Hello Rollen , How Are You'          #每个单词的首字母大写
>>> string.split(s)
['hello', 'rollen', ',', 'how', 'are', 'you']     #划分为列表 默认是以空格划分
>>> s='1+2+3'
>>> string.split(s,'+')                 #以‘+’号进行划分
['1', '2', '3']

maketrans()方法会创建一个能够被translate()使用的翻译表,可以用来改变一些列的字符,这个方法比调用replace()更加的高效。

例如下面的例子将字符串s中的‘a,改为1,‘b’改为2,‘c’改为3’:

>>> leet=string.maketrans('abc','123')
>>> s='abcdef'
>>> s.translate(leet)
'123def'
>>> leet=string.maketrans('abc','123')
>>> s='aAaBcC'
>>> s.translate(leet)
'1A1B3C'

string中的template的小例子:

import string
values = { 'var':'foo' }
t = string.Template("""
Variable : $var
Escape : $$
Variable in text: ${var}iable
""")
print 'TEMPLATE:', t.substitute(values)
s = """
Variable : %(var)s
Escape : %%
Variable in text: %(var)siable
"""
print 'INTERPOLATION:', s % values

上面的例子的输出为:

TEMPLATE:
Variable : foo
Escape : $
Variable in text: fooiable

INTERPOLATION:
Variable : foo
Escape : %
Variable in text: fooiable

但是上面的substitute如果提供的参数不足的时候,会出现异常,我们可以使用更加安全的办法,如下:

import string
values = { 'var':'foo' }
t = string.Template("$var is here but $missing is not provided")
try:print 'substitute() :', t.substitute(values)
except KeyError, err:print 'ERROR:', str(err)
print 'safe_substitute():', t.safe_substitute(values)

上面例子的输出为:

substitute() : ERROR: 'missing'
safe_substitute(): foo is here but $missing is not provided

下面来看一些template的高级用法:

import string
template_text = '''
Delimiter : %%
Replaced : %with_underscore
Ignored : %notunderscored
'''
d = { 'with_underscore':'replaced',
'notunderscored':'not replaced',
}
class MyTemplate(string.Template):delimiter = '%'idpattern = '[a-z]+_[a-z]+'
t = MyTemplate(template_text)
print 'Modified ID pattern:'
print t.safe_substitute(d)

输出为:

Modified ID pattern:

Delimiter : %
Replaced : replaced
Ignored : %notunderscored

在这个例子中,我们通过自定义属性delimiter 和 idpattern自定了规则,我们使用%替代了美元符号$,而且我们定义的替换规则是被替换的变量名要包含下环线,所以在上面的例子中,只替换了一个。

import textwrapsample_text = '''
The textwrap module can be used to format text for output in
situations where pretty-printing is desired. It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.
'''print 'No dedent:\n'
print textwrap.fill(sample_text, width=50)

输出为:

No dedent:

The textwrap module can be used to format text
for output in situations where pretty-printing is
desired. It offers programmatic functionality
similar to the paragraph wrapping or filling
features found in many text editors.

上面的例子设置宽度为50,下面的例子我们来移除缩进

import textwrapsample_text = '''
The textwrap module can be used to format text for output in
situations where pretty-printing is desired. It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.
'''dedented_text = textwrap.dedent(sample_text)
print 'Dedented:'
print dedented_text

Dedented:

The textwrap module can be used to format text for output in
situations where pretty-printing is desired. It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.

Hit any key to close this window...

下面来一个对比:

import textwrapsample_text = '''
The textwrap module can be used to format text for output in
situations where pretty-printing is desired. It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.
'''dedented_text = textwrap.dedent(sample_text).strip()
for width in [ 45, 70 ]:print '%d Columns:\n' % widthprint textwrap.fill(dedented_text, width=width)print

上面的例子的输出如下:

45 Columns:The textwrap module can be used to format
text for output in situations where pretty-
printing is desired. It offers programmatic
functionality similar to the paragraph
wrapping or filling features found in many
text editors.70 Columns:The textwrap module can be used to format text for output in
situations where pretty-printing is desired. It offers programmatic
functionality similar to the paragraph wrapping or filling features
found in many text editors.Hit any key to close this window...

我们也可以设置首行和剩余的行:

import textwrapsample_text = '''
The textwrap module can be used to format text for output in
situations where pretty-printing is desired. It offers
programmatic functionality similar to the paragraph wrapping
or filling features found in many text editors.
'''dedented_text = textwrap.dedent(sample_text).strip()
print textwrap.fill(dedented_text,
initial_indent=' ',
subsequent_indent=' ' * 4,
width=50,
)

输出为:

The textwrap module can be used to format text
    for output in situations where pretty-printing
    is desired. It offers programmatic
    functionality similar to the paragraph
    wrapping or filling features found in many
    text editors.

上面的例子设置首行缩进1个空格,其余行缩进4个空格

在文本中查找:

import re
pattern = 'this'
text = 'Does this text match the pattern?'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print 'Found "%s"\nin "%s"\nfrom %d to %d ("%s")' % \
(match.re.pattern, match.string, s, e, text[s:e])

start和end返回匹配的位置

输出如下:

Found "this"
in "Does this text match the pattern?"
from 5 to 9 ("this")

re includes module-level functions for working with regular expressions as text strings,
but it is more efficient to compile the expressions a program uses frequently. The compile() function converts an expression string into a RegexObject.

import re
# Precompile the patterns
regexes = [ re.compile(p) for p in [ 'this', 'that' ]]
text = 'Does this text match the pattern?'
print 'Text: %r\n' % text
for regex in regexes:print 'Seeking "%s" ->' % regex.pattern,if regex.search(text):print 'match!'else:print 'no match'

Text: 'Does this text match the pattern?'

Seeking "this" -> match!
Seeking "that" -> no match

The module-level functions maintain a cache of compiled expressions. However,
the size of the cache is limited, and using compiled expressions directly avoids the
cache lookup overhead. Another advantage of using compiled expressions is that by
precompiling all expressions when the module is loaded, the compilation work is shifted
to application start time, instead of to a point when the program may be responding to
a user action.

So far, the example patterns have all used search() to look for single instances of
literal text strings. The findall() function returns all substrings of the input that
match the pattern without overlapping.

import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.findall(pattern, text):print 'Found "%s"' % match

Found "ab"
Found "ab"

finditer() returns an iterator that produces Match instances instead of the
strings returned by findall().

import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.finditer(pattern, text):s = match.start()e = match.end()print 'Found "%s" at %d:%d' % (text[s:e], s, e)

Found "ab" at 0:2
Found "ab" at 5:7

转载于:https://www.cnblogs.com/rollenholt/archive/2012/06/05/2537348.html

Python标准库-string模块《未完待续》相关推荐

  1. Python标准库queue模块原理浅析

    Python标准库queue模块原理浅析 本文环境python3.5.2 queue模块的实现思路 作为一个线程安全的队列模块,该模块提供了线程安全的一个队列,该队列底层的实现基于Python线程th ...

  2. Python标准库threading模块Condition原理浅析

    Python标准库threading模块Condition原理浅析 本文环境python3.5.2 threading模块Condition的实现思路 在Python的多线程实现过程中,在Linux平 ...

  3. Python标准库asyncio模块基本原理浅析

    Python标准库asyncio模块基本原理浅析 本文环境python3.7.0 asyncio模块的实现思路 当前编程语言都开始在语言层面上,开始简化对异步程序的编程过程,其中Python中也开始了 ...

  4. python的csv标准库,Python标准库: csv模块——CSV文件的读写

    CSV简介 CSV(Comma Separated Values,逗号分隔值)也称字符分隔值,因为分隔符可以不是逗号,是一种常用的文本格式,用以存储表格数据,包括数字或者字符.很多程序在处理数据时都会 ...

  5. Python 标准库 functools 模块详解

    functools 官方文档:https://docs.python.org/zh-cn/3/library/functools.html Python 标准模块 --- functools:http ...

  6. 嵌入式开发日记(8)——用python实现FIR滤波(未完待续)

    第一阶段的方法是根据单位时间内的加速度绝对值差值来判断震颤程度,存在很多问题.因此设想采用更加高级的算法来加以改进. 这部分的主要工作有:  1 学习数字信号处理的滤波算法,重点学习python下使用 ...

  7. Python标准库--time模块的详解

    time模块 - - -时间获取和转换 在我们学习time模块之前需要对以下的概念进行了解: 时间戳:时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08 ...

  8. Python标准库——collections模块的Counter类

    更多16 最近在看一本名叫<Python Algorithm: Mastering Basic Algorithms in the Python Language>的书,刚好看到提到这个C ...

  9. Python 标准库 - Pprint 模块 - 用于打印 Python 数据结构

    使用 pprint 模块 pprint 模块( pretty printer ) 用于打印 Python 数据结构. 当你在命令行下打印特定数据结构时你会发现它很有用(输出格式比较整齐, 便于阅读). ...

最新文章

  1. 数据驱动安全架构升级---“花瓶”模型迎来V5.0(二)
  2. form表单获取input对象浏览器区别
  3. LiveVideoStackCon讲师热身分享 ( 六 ) —— 多媒体业务QoEQoS指标设计与监控
  4. 利用python画分形图_使用 Python 绘制 Mandelbrot 分形图
  5. Java学习笔记8-1——汇编语言入门
  6. html显示pcd,PCD5043 Datasheet(数据表) 10 Page - NXP Semiconductors
  7. mysql性能优化学习_mysql学习——性能优化之sql优化
  8. 【成长之路】【python】python基础2
  9. asm冗余 oracle_ORACLE 11G RAC ASM磁盘的三种冗余模式
  10. 使用深度学习打造智能聊天机器人
  11. 传销三级的认定标准_应为传销案件中“劳务性工作人员”争取“不起诉”—传销犯罪辩护与研究(四十五)...
  12. DQL、DML、DDL、DCL的定义
  13. 从键盘任意输入一个年号,判断它是否是闰年。
  14. 修复花雨庭服务器,我的世界手机版怎么进花雨庭服务器 | 手游网游页游攻略大全...
  15. Future、FutureTask、CompletableFuture简介
  16. 新款文章,绝无仅有!微信语音aud文件转换为mp3格式
  17. 计算机科学与导论论文样例,计算机科学导论论文684413422
  18. 什么是无线cpe与AP?如何区分二者的功能?
  19. Tor网络已过时? 新匿名架构将达93Gb/s
  20. PVC石笼网的结构特性

热门文章

  1. SpringBoot集成WebSocket案例:服务端与客户端消息互通
  2. Java发送form-data请求实现文件上传
  3. Android开发笔记(一百六十五)利用红外发射遥控电器
  4. Alipay Direct Bankpay 支付宝网银支付 (For OpenCart 2.x)
  5. 申请google Map api key for android
  6. 國外空間亂碼解決方法
  7. gitlab 安装_安装Gitlab-注意端口
  8. 运行gclient一直没反应_安川变频器通电没反应维修措施分享
  9. 计算机系统-内存的最小存储单元
  10. postgresql fdw mysql_mysql同步数据到PostgreSQL(使用mysql_fdw)