天天看點

在 Python 中如何使用 format 函數?

作者:海擁科技

在 Python 中,format 函數是一種非常常用的字元串格式化方法,它可以用于将一個字元串中的占位符替換成具體的數值、字元串等内容,進而生成一個新的字元串。本文将介紹如何使用 format 函數進行字元串格式化,包括基本用法、格式化參數和進階格式化方法。

基本用法

format 函數的基本用法非常簡單,它可以接受一個或多個參數,并将它們插入到一個字元串中的占位符位置上。下面是一個簡單的示例:

name = 'John'
age = 30
print('My name is {} and I am {} years old.'.format(name, age))
           

在這個示例中,我們使用 format 函數将字元串中的兩個占位符 {} 分别替換成了變量 name 和 age 的值,生成了一個新的字元串。輸出結果為:

My name is John and I am 30 years old.
           

在 format 函數中,每個占位符 {} 都對應一個參數,可以按照位置順序依次替換。如果需要在字元串中使用大括号 {},可以使用雙大括号 {{}} 來轉義,例如:

print('I like {} and {{}}'.format('Python'))
           

輸出結果為:

I like Python and {}
           

格式化參數

除了基本的占位符外,format 函數還支援各種格式化參數,可以用于控制字元串的格式和對齊方式。下面是一些常用的格式化參數:

  • {:<n}:左對齊,占用 n 個字元的寬度。
  • {:>n}:右對齊,占用 n 個字元的寬度。
  • {:^n}:居中對齊,占用 n 個字元的寬度。
  • {:.nf}:保留 n 位小數。
  • {:,}:千位分隔符。

例如,我們可以使用格式化參數來對輸出進行對齊和格式化:

# 左對齊,占用 10 個字元的寬度
print('{:<10} {:<10}'.format('Name', 'Age'))
print('{:<10} {:<10}'.format('John', 30))
print('{:<10} {:<10}'.format('Mike', 25))

# 保留 2 位小數
print('The value of pi is approximately {:.2f}.'.format(3.141592653589793))

# 千位分隔符
print('The population of China is {:,}.'.format(1400000000))
           

輸出結果為:

Name       Age       
John       30        
Mike       25        
The value of pi is approximately 3.14.
The population of China is 1,400,000,000.
           

格式化參數可以大大增強 format 函數的靈活性和可用性,使得我們可以更友善地控制字元串的輸出格式。

進階格式化方法

除了基本的占位符和格式化參數外,format 函數還提供了一些進階的格式化方法,可以實作更複雜的字元串格式化需求。下面是一些常用的進階格式化方法:

通過位置和名稱指定參數

在 format 函數中,可以通過位置和名稱兩種方式指定參數。例如,我們可以使用位置參數來控制占位符的順序:

print('{0}, {1}, {2}'.format('a', 'b', 'c'))
           

輸出結果為:

a, b, c
           

也可以使用名稱參數來指定占位符對應的參數:

print('{name}, {age}'.format(name='John', age=30))
           

輸出結果為:

John, 30
           

使用字典和清單作為參數

在 format 函數中,還可以使用字典和清單作為參數,用于實作更靈活的字元串格式化。例如,我們可以使用清單來控制占位符的順序:

mylist = ['John', 30]
print('My name is {0[0]} and I am {0[1]} years old.'.format(mylist))
           

輸出結果為:

My name is John and I am 30 years old.
           

也可以使用字典來指定占位符對應的參數:

mydict = {'name': 'John', 'age': 30}
print('My name is {name} and I am {age} years old.'.format(**mydict))
           

輸出結果為:

My name is John and I am 30 years old.
           

使用 f-string

在 Python 3.6 及以上版本中,還可以使用 f-string(也稱為格式化字元串字面值)來進行字元串格式化。f-string 的文法非常簡單,隻需要在字元串前加上 f 字首,然後使用大括号 {} 來包含占位符和表達式即可。例如:

name = 'John'
age = 30
print(f'My name is {name} and I am {age} years old.')
           

輸出結果與之前的示例相同:

My name is John and I am 30 years old.
           

f-string 不僅文法簡單,而且性能也比 format 函數更高效。是以,如果使用的 Python 版本支援 f-string,建議盡量使用它來進行字元串格式化。

總結

format 函數是 Python 中常用的字元串格式化方法,可以用于将一個字元串中的占位符替換成具體的數值、字元串等内容,進而生成一個新的字元串。在使用 format 函數時,可以使用基本的占位符、格式化參數和進階的格式化方法,來實作各種字元串格式化需求。另外,在 Python 3.6 及以上版本中,還可以使用 f-string 來進行字元串格式化,這種方法更為簡單和高效。

在 Python 中如何使用 format 函數?