python format函数的用法是什么

46次阅读
没有评论

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

Python 的 format 函数用于格式化字符串,将一个或多个值插入到字符串中。它可以在字符串中指定占位符,然后使用 format 函数将对应的值替换到占位符的位置上。

format 函数的基本语法如下:

formatted_string = " 字符串模板 ".format(value1, value2, ...)

在字符串模板中,可以使用花括号 {} 作为占位符,然后在 format 函数中按顺序传入对应的值来替换这些占位符。

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

  1. 顺序替换
name = "Alice"
age = 25
text = "My name is {} and I am {} years old.".format(name, age)
print(text)  # 输出: My name is Alice and I am 25 years old.
  1. 根据索引替换
name = "Alice"
age = 25
text = "My name is {0} and I am {1} years old.".format(name, age)
print(text)  # 输出: My name is Alice and I am 25 years old.
  1. 根据关键字替换
name = "Alice"
age = 25
text = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(text)  # 输出: My name is Alice and I am 25 years old.
  1. 格式化数字
pi = 3.14159265359
formatted_pi = "{:.2f}".format(pi)
print(formatted_pi)  # 输出: 3.14
  1. 对齐和填充
text = "{:<10}{}".format("left", "right")
print(text)  # 输出: "left      right"

以上只是 format 函数的一些常用用法,还有更多的格式化选项可以参考官方文档。

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

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