在这里会介绍使用字符串格式化其他值,并简单了解一下利用字符串的分割、连接‘搜索等方法能做些什么。
基本字符串操作
所有标准的序列操作(索引、分片、乘法、判断成员资格、求长度、取最大值、取最小值)同样适用。字符串是不可变的,下面看一个实例说明这点。
>>> website = 'http://www.python.org'
>>> website[-3:] = 'com'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
字符串格式化
字符串格式化使用字符串格式化操作符即百分号%来实现。
注:%也可以用作模运算(求余)操作符
使用元组:
如果右操作符是元组的话,则其中的每一个元素都单独格式化,每个值都需要一个对应的转换说明符。
>>> format = 'Hello, %s,%s enough for ya? '
>>> values = ('world', 'Hot')
>>> print format % values
Hello, world,Hot enough for ya?
模板字符串
>>> from string import Template
>>> s = Template('$x, glorious $x !')
>>> s.substitute(x='slurm')
'slurm, glorious slurm !'
可以使用$$插入美元符号
>>> s = Template("Make $$ selling $x !")
>>> s.substitute(x='slurm')
'Make $ selling slurm !'
使用字典变量提供值/名称对
>>> 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 '
safe_substitute()不会因缺少值或者不正确使用$字符而出错
字符串格式化转换表
转换类型 | 含义 |
---|---|
d, i | 带符号的十进制整数 |
o | 不带符号的八进制 |
u | 不带符号的十进制 |
x,X | 不带符号的十六进制(小写/大写) |
e,E | 科学计算法表示的浮点数(小写/大写) |
f,F | 十进制浮点数 |
g,G | 如果指数大于-4或者小于精度值则和e/E相同,其他情况与f/F相同 |
c | 单字符 |
r | 字符串(使用repr转换任意python对象) |
s | 字符串(使用str转换任意python对象) |
基本转换说明符顺序的含义:
1. %字符:标记转换说明符的开始
2. 转换标志(可选):-表示左对齐;+表示在转换值之前要加上正负号;’‘’‘表示正数之前保留空格;0表示转换值若位数不够则用0填充。
3. 最小字符宽度(可选)
4. 点(.)后面跟精度值
#!/usr/bin/env python
# coding=utf-8
#使用给定的宽度打印格式化后的价格列表
width = input('Please enter width: ')
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
format = '%-*s%*.2f'
print '='* width
print header_format % (item_width, 'Item', price_width, 'Price')
print '-'*width
print format % (item_width, 'Apples', price_width, 0.4)
print format % (item_width, 'Pears', price_width, 0.5)
print format % (item_width, 'Cantloupes', price_width, 1.51)
print format % (item_width, 'Dried Apricots(16 oz.)', price_width, 12.4)
print format % (item_width, 'Prunes (4 lbs)', price_width, 99)
print '='*width
Please enter width: 36
====================================
Item Price
------------------------------------
Apples 0.40
Pears 0.50
Cantloupes 1.51
Dried Apricots(16 oz.) 12.40
Prunes (4 lbs) 99.00
====================================
字符串方法
find join lower replace split strip translate
更多请看Python教程