字符串进阶
1、string模板提供另外一个格式化的方法:模板字符串,substitute这个模板方法会用传递进来的关键词参数foo替换字符串中的$foo
>>> from string import Template
>>> s = Template('$x, glorious $x!')
>>> s.substitute(x='slurm')
'slurm, glorious slurm!'
除了关键词参数之外,还可以使用字典变量提供值/名称对
>>> s = Template('A $thing must never $action.')
>>> d={}
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his sock'
>>> s.substitute(d)
格式化操作符的右操作数可以是任意类型,如果是元组或者映射类型(如字典),那么字符串格式化将会有所不同。
如果右操作数是元组的话,则其中的每一个元素都会被单独格式化,每个值都需要一个对应的转换说明符。
>>> '%s plus %s equals %s' % (1,1,2)
'1 plus 1 equals 2'
基本转换说明符的项的顺序:
1:%字符:标记转换说明符的开始
2:转换标志:- 表示左对齐; + 表示在转换值之前要加上正负号;“”(空白字符)表示正数之前保留空格;0表示转换值若位数不够则用0填充
3:最小字段宽度:转换后的字符串至少应该具有该值的宽度。如果是*,则宽度会从值元组中读出。
4:点(.)后跟精度值:如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将会从元组中读出。
>>> f=1.2234
>>> '%4f' %f
'1.223400'
>>> '%8f' %f
'1.223400'
>>> '%10f' %f
' 1.223400'
>>> '%-10f' %f
'1.223400 '
>>> '%-10.3f' %f
'1.223 '
>>> '%-10.3f' % 1.2345678
'1.235 '
>>> '%-.3s' % 1.2345678
'1.2'
>>> '%-.3r' % 1.2345678
'1.2'
>>> '%-.5r' % 1.2345678
'1.234'
可以使用*(星号)作为字段宽度或者精度(或者两者都使用*),此时数值会从元组参数中读出
>>> '%.*s' % (5,'Guido van Rossum')
'Guido'
>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)
+10
-10
字符串的一个例子(python 3. 3版本)
#使用给定的宽度打印格式化后的价格列表
width = input('Please enter width: ')
width = int(width)
price_width = 10
price_width = int(price_width)
item_width = int(width) - int(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, 'Apple', price_width, 0.4))
print (Format % (item_width, 'Pears', price_width, 0.4))
print (Format % (item_width, 'Cantaloupes', price_width, 0.4))
print (Format % (item_width, 'Dried Apricots(16 oz.)', price_width, 0.8))
print (Format % (item_width, 'Prunes(4 lbs.)', price_width, 12))
print ('=' * width)
>>> ================================ RESTART ================================
>>>
Please enter width: 35
===================================
Item Price
-----------------------------------
Apple 0.40
Pears 0.40
Cantaloupes 0.40
Dried Apricots(16 oz.) 0.80
Prunes(4 lbs.) 12.00
===================================
下面介绍一些有用的字符串常量:
string,digits:: 包含数字0~9的字符串
string.letters:包含所有字母的字符串
string.lowercase:包含所有小写字母的字符串
string.printable:包含所有可打印字符的字符串
string.punctuation:包含所有标点的字符串
string.uppercase:包含所有大写字母的字符串
---------------------------------------------------------------------
join方法是非常重要的字符串方法,用来连接序列中的元素
>>> dirs = '','usr','bin','env'
>>> dirs
('', 'usr', 'bin', 'env')
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print 'C:' + '\\'.join(dirs)
SyntaxError: invalid syntax
>>> print ('C:' + '\\'.join(dirs))
C:\usr\bin\env
注意一:python3里面input默认接收到的事str类型
以上案例取自《Python基础教程第二版》