跟我一起学Python之八:基本字符串和字符串格式化

来源:互联网 发布:淘宝一千多的充气娃娃 编辑:程序博客网 时间:2024/05/21 15:36

1.基本字符串操作


字符串是序列的一种,字符串是不可改变的。

>>> website='heep://www.python.org'>>> website'heep://www.python.org'>>> website[-3:]'org'

 

2.字符串格式化

[1]简单转换
精简版:

>>> format="hello, %s , %s enough for ya?"   #%号代表有一个变量,s代表是字符串类型>>> values=("world","Hot")>>> print format % values                    #格式 print 格式化 %  变量值hello, world , Hot enough for ya?
>>> format = "pi whith three decimals:%.3f"  #%号代表占位符,f代表字符串类型为浮点数,.3代表要3位小数>>> from math import pi>>> print format % pipi whith three decimals:3.142
>>> from string import Template   >>> 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 plus %s equals %s' % (1,2,3)  #如果变量为元组需要加上小括号'1 plus 2 equals 3'

%出现,说明转换开始了。

s代表字符串;
C代表一个字符;
G代表大于-4;
g代表大于-4;
f代表十进制浮点数;
e代表科学技术法;
X代表十六进制;
d代表十进制整数;


[2]字段宽度和精度

宽度

>>> '%10f' % pi'  3.141593'

 

精度

>>> '%.2f' % pi'3.14'>>> '%.5s' % 'loooooool''loooo'

 

[3]符号、对齐和0填充

0填充

>>> '%010.2f' % pi'0000003.14

 

-号代表左对齐

>>> '%-10.2f' % pi'3.14    '

 

空格填充

>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)   10  -10>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)  +10  -10


 

e.g.width=input("please enter width: ")price_width=10item_width=width-price_widthheader_format="%-*s%*s" #标题格式format="%-*s%*.2f" #数据项格式print '=' * widthprint header_format % (item_width,"Item",price_width,"Price")print '-' * widthprint 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',price_width,8)print format % (item_width,'Prunes(4,lbs.)',price_width,12)print '-' * widthplease enter width: 35===================================Item                          Price-----------------------------------Apples                         0.40Pears                          0.50Cantaloupes                    1.92Dried Apricots                 8.00Prunes(4,lbs.)                12.00-----------------------------------
原创粉丝点击