在 Python 中如何使用 format 函数?

format()函数是Python中用于字符串格式化的工具,它可以处理不同类型的数据,如变量插入、数字格式化、对齐方式以及日期时间格式。文章通过多个示例展示了format()的用法,包括基本使用、数字精度控制、文本对齐和日期时间格式化,强调了其灵活性和实用性。
摘要由CSDN通过智能技术生成

format() 函数可以用于将不同类型的数据插入到字符串中。

下面是几个使用 format() 函数的代码示例:

1. 基本用法:

age = 20
name = "Tom"
print("My name is {0} and I'm {1} years old.".format(name, age))

输出:

My name is Tom and I'm 20 years old.

2. 格式化数字:

pi = 3.1415926
print("The value of pi is approximately {0:.2f}.".format(pi))

输出:

The value of pi is approximately 3.14.

3. 指定宽度和对齐方式:

language = "Python"
print("{0:<10}".format(language)) # 左对齐
print("{0:>10}".format(language)) # 右对齐
print("{0:^10}".format(language)) # 居中对齐

输出:

Python    
    Python
  Python  

4. 格式化日期时间:

from datetime import datetime
now = datetime.now()
print("Today's date and time is {:%Y-%m-%d %H:%M:%S}".format(now))

输出:

Today's date and time is 2023-05-05 10:43:59

5. 嵌套使用:

name = "Tom"
age = 20
print("My name is {0} and I'm {1} years old. In {1} years, I will be {2} years old.".format(name, age, age+5))

输出:

My name is Tom and I'm 20 years old. In 20 years, I will be 25 years old.

总之,format() 函数非常灵活,可以用于各种各样的字符串格式化需求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值