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

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM