当前分类:python>>正文

什么是格式化输出?python编程常用的格式化输出方法

来源:互联网   更新时间:2023年5月17日  

一般来说,python编程的格式化输出常见的有三种,但实际上不止三种。除了 `f` 格式化输出与 `format()` 格式化输出之外,Python还提供了其他的字符串格式化方法,如百分号( `%` )格式化、模板字符串(Template Strings)等。百分号( `%` )格式化在一些早期版本的Python中较为常用,但现在已经不推荐使用了。模板字符串则是一种基于占位符的字符串格式化方法,它可以在一些需要动态生成HTML、XML等文本文件时较为实用。不过,对于大多数字符串格式化需求, `f` 格式化输出与 `format()` 格式化应该已经足够使用了。

方式一:f格式化输出

看个例子就明白了

name = "Alex"
age = 25
print(f"My name is {name} and I'm {age} years old.")

方式二:format格式化输出

name = "Alex"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))

方式三:%格式化输出

name = "Alex"
age = 25
print("My name is %s and I'm %d years old." % (name, age))

下面这种输出方式基本上很少使用到。

方式四:模板字符串(Template Strings)

from string import Template
 name = "Alex"
age = 25
template = Template("My name is $name and I'm $age years old.")
print(template.substitute(name=name, age=age))

四种方式的输出结果都是:

My name is Alex and I'm 25 years old.

希望本文对你有帮助!

本文固定链接:https://6yhj.com/leku-p-3818.html  版权所有,转载请保留本地址!
[猜你喜欢]

标签: python基础