《Beginning Python From Novice to Professional》学习笔记五:Advanced String

1.格式化
format='hello, %s. Your ID is %d.'
values=('thy', 38)
print format % values
---> 'hello, thy. Your ID is 38.'
如第二句如示,要修饰多个元素,可以用Tuple,也可以用Dictionary(但不可以用List,因为List会被认为仅仅是一个单值

2.模板(此功能不是内置的,因此要导入string库)
import string
s=string.Template('$name is an amzaing girl $$!')
s.substitute(name='Rose')
---> 'Rose is an amzaing girl $!'   #注意最后一个$

但以上写法在下面例子中会出问题
s=string.Template('$name2nd is a great empire $$!')
s.substitute(name='Henry')

因此编译器无法区分name是单词的一部分。可改为
s=string.Template('${name}2nd is a great empire $$!')
s.substitute(name='Henry')
---> 'Henry2nd is a great empire $!'

还可以用Dictionary中的Value-Name对来替换。
s = Template('A $thing must never $action.')
d = {}   #建一个空的Dictionary
d['thing'] = 'true man'
d['action'] = 'let his girl cry'
s.substitute(d)
---> 'A good man must never let his girl cry.'

3.精度
'%10.2f' % 2 ---> '      2.00'
'%010.2f' % 2 ---> '0000002.00'   #注意在10之前的0不可更换,因为若为其它数字,会与10成为整体;若为字母,会成为转义字符
'%10.2s' % 'thy' ---> '        th'
'%.2s' % 'thy' ---> 'th'
但是'%.*s' % 'thy'会出错,这时一定要接Tuple对象,其中Tuple的第一项用来替换精度中的*,可用于由用户定制精度。
'%.*s' % (5, 'Guidovan')
---> 'Guido'
'%*.3s' % (5, 'Guidovan')
---> '  Gui'

附上一段《Beginning Python From Novice To Professional 2nd》中十分精致的示例代码:
# Print a formatted price list with a given width 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, 'Cantaloupes', 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
--->
The following is a sample run of the program:
Please enter width: 35
===================================
Item                          Price
———————————————————
Apples                         0.40
Pears                          0.50
Cantaloupes                    1.92
Dried Apricots (16 oz.)        8.00
Prunes (4 lbs.)               12.00
===================================

(由于网页发布的原因,中间不对齐,事实上Item项是左对齐,Price项是右对齐)

你可能感兴趣的:(String,list,python,header,编译器,Dictionary)