Python 格式化的方法

在Python中,我们可以使用字符串的format()方法或f-string这两种方法来进行格式化。

1、使用format()方法:使用该方法,我们可以通过占位符{}来表示被替换的值,其中可以单独使用{}或添加变量参数来指定相应的值。如:

name = "Alice"
age = 25
height = 1.65

# 使用位置参数
message = "My name is {}, I'm {} years old, and my height is {} meters.".format(name, age, height)
print(message)
# 输出:My name is Alice, I'm 25 years old, and my height is 1.65 meters.

# 使用关键字参数
message = "My name is {name}, I'm {age} years old, and my height is {height} meters.".format(name=name, age=age, height=height)
print(message)
# 输出:My name is Alice, I'm 25 years old, and my height is 1.65 meters.

2、使用f-string:该方法是从Python3.6开始引入的方法。也是使用占位符{}来表示被替换的值,并通过变量名指定相应的值。如:

name = "Alice"
age = 25
height = 1.65

message = f"My name is {name}, I'm {age} years old, and my height is {height} meters."
print(message)
# 输出:My name is Alice, I'm 25 years old, and my height is 1.65 meters.

除了以上的最基本的字符串替换,我们还可以在占位符中指定格式化选项,如指定浮点数的小数位数、对齐方式等。如:

pi = 3.1415926

# 指定小数位数为两位
formatted_pi = "{:.2f}".format(pi)
print(formatted_pi)  # 输出:3.14

# 指定总宽度为8,并右对齐
formatted_pi = "{:8.2f}".format(pi)
print(formatted_pi)  # 输出:    3.14

# 使用 f-string,指定小数位数为两位
formatted_pi = f"{pi:.2f}"
print(formatted_pi)  # 输出:3.14

你可能感兴趣的:(python,java,开发语言)