方法 | 描述 |
---|---|
str.format(*args, **kwargs) | 進行格式化字串運算 |
舉例示範如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | a = "{0} + {1} = {2}" b = "Welcome to the desert... of the {0}." c = "What is {one}? How do you define {two}?" d = "There is no {}." print (a) print (a. format ( 3 , 4 , 3 + 4 )) print () print (b) print (b. format ( "truth" )) print () print (c) print (c. format (two = "truth" , one = "it" )) print () print (d) print (d. format ( "spoon" )) print () # 《程式語言教學誌》的範例程式 # 檔名:strformat.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 12 月 |
執行結果如下

格式化字串中的大括弧表示所要替代的部份,可以用從 0 開始的數字標記,就會以 format() 中的參數依序替換,或是給定名稱,如上例中的 one 及 two ,這樣 format() 也須指定相對應的名稱。 3.1 版以後,數字可以不加。
中英文術語對照 | |
---|---|
字串 | string |
型態 | type |
方法 | method |
沒有留言:
張貼留言