Python format() 函式



Python 的 **format() 函式** 根據格式化程式返回給定值的指定格式。

**format()** 是一個 內建函式,可用於各種目的,例如建立格式良好的字串、特定型別的格式化、數字格式化、字串對齊和填充等。

語法

以下是 Python **format()** 函式的語法:

format(value, formatSpec = '')

引數

Python **format()** 函式接受以下引數:

  • **value** − 它表示需要格式化的值(數字字串)。

  • **formatSpec** − 它表示指定如何格式化值的格式。其預設值為一個空字串。

返回值

Python **format()** 函式根據指定的格式返回傳遞值的格式化表示。

format() 函式示例

練習以下示例以瞭解如何在 Python 中使用 **format()** 函式。

示例:format() 函式的使用

以下示例顯示如何使用 Python format() 函式將給定數字格式化為特定形式。此處,此函式應用於多個數字以將其格式化為不同的形式。

numOne = 5100200300
formattedNum = format(numOne, ",") 
print("Formatting the number using separator:", formattedNum)
   
numTwo = 12.756
formattedNum = format(numTwo, ".2%")
print("Rounding the given number:",formattedNum)
   
numThree = 500300200
formattedNum = format(numThree, "e")
print("Converting number into exponential notation:", formattedNum)
   
numFour = 541.58786
formattedNum = format(numFour, ".2f")
print("Formatting number to two decimal places:", formattedNum)  

執行上述程式時,它會產生以下結果:

Formatting the number using separator: 5,100,200,300
Rounding the given number: 1275.60%
Converting number into exponential notation: 5.003002e+08
Formatting number to two decimal places: 541.59

示例:將十進位制轉換為二進位制、八進位制和十六進位制格式

Python format() 函式可用於將給定數字轉換為其對應的二進位制、八進位制和十六進位制表示形式,如下例所示。

nums = 124
binaryNum = format(nums, "b")
octalNum = format(nums, "o")
hexNum = format(nums, "x")
print("Converting number into Binary:", binaryNum)  
print("Converting number into Octal:", octalNum)  
print("Converting number into Hexadecimal:", hexNum)  

執行上述程式時,它會產生以下結果:

Converting number into Binary: 1111100
Converting number into Octal: 174
Converting number into Hexadecimal: 7c

示例:重寫 __format__ 類方法

透過重寫類中的“__format__”方法,我們可以自定義該類物件的格式化方式。下面的程式碼演示了這一點。

import datetime

class DefDate:
   def __init__(self, year, month, day):
      self.date = datetime.date(year, month, day)

   def __format__(self, formatSpec):
      return self.date.strftime(formatSpec)

formattedDate = DefDate(2024, 4, 17)
print("Date after formatting:")
print(format(formattedDate, "%B %d, %Y"))

上述程式碼的輸出如下:

Date after formatting:
April 17, 2024
python_built_in_functions.htm
廣告