您的位置:首页 > 编程语言 > Python开发

[Python 03] 字符串

2013-01-17 17:37 148 查看
第3章 使用字符串

  字符串的分割,联接,搜索。

3.1 基本字符串操作

 标准的序列操作 (索引,分片,判断成员资格,求长度,最值) 对字符串同样使用。

3.2 字符串格式化
>>> format = "Hello, %s. %s enough for ya?"  # %s
>>> values = ('world', 'Hot')
>>> print format %values
Hello, world. Hot enough for ya?

>>> format = "Pi with three decimals : %.3f" # %f
>>> from math import pi
>>> print format % pi
Pi with three decimals : 3.142

>>> from string import Template              # 模板字符串 string
>>> s = Template('$x, glorious $x!')
>>> s.substitute(x='slurm')
'slurm, glorious slurm!'
>>> s = Template("It's ${x}tastic!")
>>> s.substitute(x='slurm')
"It's slurmtastic!"

>>> s = Template('A $thing must never $action.')  # 字典变量 值/名对
>>> d = {}
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'
转换元组
>>> '%s plus %s equals %s' % (1, 1, 2)
'1 plus 1 equals 2'
>>> '%.5s' % 'Hello World'  #字段宽度和精度 %10.2f什么的
'Hello'
* 符号,对齐,和 0 填充 *
>>> '%010.2f' % pi
'0000003.14'
>>> '%-10.2f' % pi
'3.14      '
>>> '%+10.2f' % pi
'     +3.14'
* 字符串方法 *

 字符串常量

 (1) string.digits 包含数字 0~9 的字符串

 (2) string.letters 包含所有字母的字符串

 (3) string.lowercase 包含所有小写字母的字符串

 (4) string.printable 包含所有可打印字符的字符串

 (5) string.punctuation 包含所有标点的字符串

 (6) string.uppercase 包含所有大写字母的字符串

 *1 find  这个方法还可以接受可选的 起始点 和 结束点 参数。
>>> title = "Hello_world good"
>>> title.find('llo')
2
>>>
*2 join 是 split 的逆方法
>>> seq = ['1', '2', '3', '4', '5']
>>> fu = '+'
>>> fu.join(seq)
'1+2+3+4+5'
*3 lower
>>> 'Tomato Heelo world'.lower()
'tomato heelo world'
* replace
>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test'
*4 split
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
*5 strip()  返回去除两侧空格的字符串
*6 translate
>>> from string import maketrans
>>> table = maketrans('cs', 'kz')
>>> "this is ok world".translate(table)
'thiz iz ok world'
* 小结 *

 (1) 字符串格式化

 (2) 字符串方法

列表,字符串和字典 是Python中最重要的3种数据类型。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: