string.format

string.format在不同数据类型中的应用

小樊
81
2024-10-16 07:17:03
栏目: 编程语言

string.format 是 Python 中的一个非常有用的函数,它允许你使用占位符 {} 在字符串中嵌入变量,并通过格式化操作来生成新的字符串。这个函数可以处理不同类型的数据,并且提供了多种格式化选项。以下是一些 string.format 在不同数据类型中的应用示例:

  1. 整数和浮点数: 使用 {} 作为占位符,并在其中指定宽度和小数点后的位数。
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. 字符串: 直接将字符串作为参数传递给 format 方法,并在占位符中使用大括号 {}
greeting = "Hello"
name = "Alice"
print("{} {}".format(greeting, name))

输出:

Hello Alice
  1. 列表和元组: 使用索引来访问列表或元组中的元素。
fruits = ["apple", "banana", "cherry"]
print("My favorite fruits are: {}.".format(', '.join(fruits)))

输出:

My favorite fruits are: apple, banana, cherry.
  1. 字典: 使用键来访问字典中的值。
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 还支持一些特殊的格式化选项,如对齐、数字格式化和字符串格式化。
# 对齐示例
print("{:<10} {:>10}".format("Name", "Age"))  # 左对齐和右对齐

# 数字格式化示例
print("{:0>8} {:0>8}".format(123456789, 987654321))  # 补零和对齐

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

输出:

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

这些示例展示了 string.format 在处理不同类型数据时的灵活性和强大功能。

0
看了该问题的人还看了