溫馨提示×

python format函數(shù)用法

小億
103
2024-01-08 15:21:13
欄目: 編程語言

Python中的format函數(shù)是用來格式化輸出的,可以將一個字符串中的占位符替換為指定的值。

基本用法如下:

string.format(value1, value2, ...)

其中,string是一個字符串,可以包含一個或多個占位符,占位符用大括號 {} 表示。value1, value2, ... 是要替換占位符的值,可以是任意類型的對象。

例子:

name = "Alice"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))

輸出:

My name is Alice and I'm 25 years old.

在占位符中可以使用一些格式規(guī)范來控制輸出的樣式。常用的格式規(guī)范有:

  • :d:十進制整數(shù)
  • :f:浮點數(shù)
  • :.2f:保留小數(shù)點后兩位的浮點數(shù)
  • :s:字符串
  • :{length}:指定字符串的最小長度為length,不夠時用空格填充
  • :{length}.{precision}:指定浮點數(shù)的最小長度為length,并保留小數(shù)點后precision

例子:

salary = 10000
print("My monthly salary is {:,} dollars.".format(salary))

輸出:

My monthly salary is 10,000 dollars.
temperature = 36.6
print("Body temperature: {:.1f} °C".format(temperature))

輸出:

Body temperature: 36.6 °C

這只是format函數(shù)的基本用法和一部分常用的格式規(guī)范,實際上format函數(shù)還支持更多的功能和格式規(guī)范,可以根據需求進行進一步學習和使用。

0