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
  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不在同一频道上的呆子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值