字符串格式化:%,左侧放字符串,右侧放希望被格式化的值,通常为元组

>>> format = "Hello, %s, %s enough for ya?"

>>> values = ('world', 'Hot')

>>> print format % values

Hello, world, Hot enough for ya?

 

如果在格式化字符串里面包括百分号,那么必须使用%%

 

模板字符串:类似于shell中的变量替换

1  >>> from string import Template

>>> s = Template('$x, galourious $x!')

>>> s.substitute(x='slurm')

'slurm, galourious slurm!'

2)如果替换字段只是一部分则参数名需要用括号括起来

>>> s = Template("It's ${x}tastic!")

>>> s.substitute(x='slurm')

"It's slurmtastic!"

3)使用$$ 插入美元符号

>>> s = Template("Make $$ selling $x!")

>>> s.substitute(x='slurm')

'Make $ selling slurm!'

4)使用字典变量提供值/名称对

>>> 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'

 

基本转换说明符

1)简单转换

#%s字符串

>>> 'Price of eggs : $%s' % 42

'Price of eggs : $42'

#%x,不带符号的十六进制

>>> 'Hexadecimal Price of eggs : %x' % 42

'Hexadecimal Price of eggs : 2a'

#%f,十进制浮点数

>>> from math import pi

>>> 'Pi : %f....' % pi

'Pi : 3.141593....'

#%i,带符号的十进制整数

>>> 'very inexact estimate of pi : %i' % pi

'very inexact estimate of pi : 3'

#%s,字符串(使用str转换任意Python对象)

>>> 'Using str : %s' % 42L

'Using str : 42'

#%r,字符串(使用repr转换任意Python对象)

>>> 'Using repr: %r' % 42L

'Using repr: 42L'

2)字符宽度和精度

字符宽度:转换后的值所保留的最小字符个数

精度:(对于数字转换)结果中应包含的小数位数

(对于字符串转换来说)转换后的值所能包含的最大字符个数

表示格式:字符宽度.精度,若给出精度,则必须包含点号

>>> '%.5s' % 'Guido van Rossum'

'Guido'

使用*(星号)作为字段宽度或者精度,此时数值会从元组参数中读出

>>> '%.*s' % (5, 'Guido Van Rossum')

'Guido'

3)符号、对齐和补充

在字段宽度和精度值之前,还可以放置一个“标志”,该标志可以是零、加号、减号或空格

>>> '%010.2f' % pi

'0000003.14'          =>包含小数点位

-减号表示左对齐

示例:

#! /usr/bin/env python

 

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, 'Cantaloups', price_width, 1.92)

print format % (item_width, 'Dried Apricots(16 oz.)', price_width, 8)

print format % (item_width, 'Prunes(4 lbs)', price_width, 12)

 

print '=' * width

 

[root@bogon wangdong]# python format_str.py

Please enter width: 35

===================================

Item                          Price

-----------------------------------

Apples                         0.40

Pears                          0.50

Cantaloups                     1.92

Dried Apricots(16 oz.)         8.00

Prunes(4 lbs)                 12.00

===================================