python字符串格式化 学习一

1、基础字符串操作

所有标准的序列操作(索引,[:],*,in,not in ,len,min,max,sorted,reversed,zip,sum,enumerate)对于字符串同样适用。但是字符串都是不可变的。因此,类似以下分片赋值是不合法的:

>>> website="www.letv.com"
>>> print website[3]
.
>>> website[3]='b'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

2、精简版字符串格式化

字符串格式化使用字符串格式化操作符,即%来实现。在%的左侧放置一个字符串(格式化字符串),而右侧则放置希望格式化的值。可以使用一个值,如一个字符串或者数字,也可以使用多个值的元组或者字典。一般情况下使用元组:

>>> format = 'Hello, %s. %s enough for ya?'
>>> values = ('world', 'Hot')              
>>> print format % values
Hello, world. Hot enough for ya?

注:(1)如果使用列表或者其他序列代替元组,那么序列就会被解释成一个值。只有元组和字典可以格式化一个以上的值。

       (2)如果要在格式化字符串里面包括百分号,那么必须使用%%,这样Python就不会将百分号误认为是转换说明符了。

 

>>> format = 'The rate is %s%, so low'
>>> values = 31.0
>>> print format % values
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

 

>>> format = 'The rate is %s%%, so low'
>>> values = 31.0                      
>>> print format % values              
The rate is 31.0%, so low

如果要格式化实数,可以使用f说明符类型,同时提供所需要的精度:一个句点再加上希望保留的小数位数。因为格式化说明符总是以表示类型的字符结束,所以精度应该放在类型字符的前面:

 

>>> format = 'Pi with three decimals: %.3f'
>>> from math import pi 
>>> print format % pi
Pi with three decimals: 3.142

 

 

格式化操作符的右操作数可以是任何东西,如果是元组或者映射类型,那么字符串格式化将会有所不同。

如果右操作数是元组的话,则其中的每一个元素都会被单独格式化,每一值都需要一个对应的转换说明符。

注意:如果需要转换的元组作为转换表达式的一部分存在,那么必须将它用圆括号括起来,以避免错:

>>> '%s plus %s equals %s' % (1, 1, 2)  
'1 plus 1 equals 2'
>>> '%s plus %s equals %s' % 1, 1, 2 # Lacks parentheses! 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

 

 

 

 

 

 

posted on 2012-10-12 10:36  mingaixin  阅读(22817)  评论(0编辑  收藏  举报