python的format方法怎么使用

44次阅读
没有评论

共计 813 个字符,预计需要花费 3 分钟才能阅读完成。

Python 中的 format 方法可以用于格式化字符串。它可以通过在字符串中插入占位符 {},然后使用 format 方法来填充这些占位符。

format 方法的基本语法如下:

string.format(value1, value2, ...)

其中,string 是要格式化的字符串,value1, value2, …是要插入的值。

以下是一些常见的用法示例:

  1. 简单用法:
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

输出:My name is Alice and I am 25 years old.

  1. 指定顺序:
name = "Alice"
age = 25
print("My name is {0} and I am {1} years old.".format(name, age))

输出:My name is Alice and I am 25 years old.

  1. 命名参数:
name = "Alice"
age = 25
print("My name is {name} and I am {age} years old.".format(name=name, age=age))

输出:My name is Alice and I am 25 years old.

  1. 格式化数字:
num = 3.1415926
print("The value of pi is {:.2f}".format(num))

输出:The value of pi is 3.14

  1. 格式化日期和时间:
import datetime
now = datetime.datetime.now()
print("Current date and time is {:%Y-%m-%d %H:%M:%S}".format(now))

输出:Current date and time is 2022-05-10 15:30:00

这只是 format 方法的一些简单用法,还有其他更高级的用法,比如对齐,填充等,可以根据需要进一步研究。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计813字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)