天天看點

Python format 格式化函數-學習日志-20210410

Python format 格式化函數-學習日志-20210410

自2.6版本 以來,一種格式化字元串的函數 str.format()的出現,增強了字元串格式化的功能。基本文法是通過 {} 和 : 來代替以前的 % 。format 函數可以接受不限個參數,位置可以不按順序。

>>>"{} {}".format("hello", "world")    # 不設定指定位置,按預設順序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 設定指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 設定指定位置
'world hello world'
           

有點類似Java中參數式的查詢注入操作,參數化查詢 ( parameterized queries ),即 SQL 語句中使用參數綁定( ? 占位符 ) 和 PreparedStatement,如

// use ? to bind variables
String sql = "SELECT * FROM users WHERE name= ? ";
PreparedStatement ps = connection.prepareStatement(sql);
// 參數 index 從 1 開始
ps.setString(1, name);
           
class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 為: {0.value}'.format(my_value))  # "0" 是可選的



輸出結果為:
    value 為: 6
           

數字格式化(具體的各種參數符号詳見---手冊)

>>> print("{:.2f}".format(3.1415926))
3.14

           

此外我們可以使用大括号 {} 來轉義大括号,如下執行個體:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print ("{} 對應的位置是 {{0}}".format("runoob"))



輸出結果為:
runoob 對應的位置是 {0}