string.format在不同數(shù)據(jù)類型中的應(yīng)用

小樊
81
2024-10-16 07:17:03

string.format 是 Python 中的一個(gè)非常有用的函數(shù),它允許你使用占位符 {} 在字符串中嵌入變量,并通過(guò)格式化操作來(lái)生成新的字符串。這個(gè)函數(shù)可以處理不同類型的數(shù)據(jù),并且提供了多種格式化選項(xiàng)。以下是一些 string.format 在不同數(shù)據(jù)類型中的應(yīng)用示例:

  1. 整數(shù)和浮點(diǎn)數(shù): 使用 {} 作為占位符,并在其中指定寬度和小數(shù)點(diǎn)后的位數(shù)。
age = 25
salary = 5000.75
print("I am {} years old and my salary is {:.2f}.".format(age, salary))

輸出:

I am 25 years old and my salary is 5000.75.
  1. 字符串: 直接將字符串作為參數(shù)傳遞給 format 方法,并在占位符中使用大括號(hào) {}。
greeting = "Hello"
name = "Alice"
print("{} {}".format(greeting, name))

輸出:

Hello Alice
  1. 列表和元組: 使用索引來(lái)訪問(wèn)列表或元組中的元素。
fruits = ["apple", "banana", "cherry"]
print("My favorite fruits are: {}.".format(', '.join(fruits)))

輸出:

My favorite fruits are: apple, banana, cherry.
  1. 字典: 使用鍵來(lái)訪問(wèn)字典中的值。
person = {"name": "Bob", "age": 30, "city": "New York"}
print("My name is {} and I live in {}.".format(person["name"], person["city"]))

輸出:

My name is Bob and I live in New York.
  1. 自定義格式化string.format 還支持一些特殊的格式化選項(xiàng),如對(duì)齊、數(shù)字格式化和字符串格式化。
# 對(duì)齊示例
print("{:<10} {:>10}".format("Name", "Age"))  # 左對(duì)齊和右對(duì)齊

# 數(shù)字格式化示例
print("{:0>8} {:0>8}".format(123456789, 987654321))  # 補(bǔ)零和對(duì)齊

# 字符串格式化示例
print("{:^20} {:^20}".format("Hello", "World"))  # 居中對(duì)齊

輸出:

Name          Age         
------------  ------------
123456789     987654321   
                Hello        World

這些示例展示了 string.format 在處理不同類型數(shù)據(jù)時(shí)的靈活性和強(qiáng)大功能。

0