Python中输出格式主要有以下几种:
% 操作符(不推荐使用)
使用格式字符串`%`和相应的占位符(如`%s`、`%d`、`%f`等)进行格式化。
示例:`print("My name is %s and I am %d years old." % (name, age))`
str.format() 方法
使用`.format()`方法,可以通过位置参数或关键字参数指定占位符的内容。
示例:`print("My name is {} and I am {} years old.".format(name, age))`
f-string(推荐使用)
在Python 3.6及更高版本中引入,使用`f`前缀的字符串字面值进行格式化。
示例:`print(f"My name is {name} and I am {age} years old.")
模板字符串
使用`string.Template`类进行字符串模板的替换。
示例:`from string import Template; t = Template("Hello, $name!"); print(t.substitute(name="World"))`
print() 函数的参数
`sep`参数定义不同项之间的分隔符。
`end`参数定义字符串的结束字符。
示例:`print("Hello", "World", sep=", ", end="!\n")`
多行字符串
使用三个引号(`'''`或`"""`)创建多行字符串。
示例:`print("""Hello\nWorld""")`
以上是Python中常见的输出格式方法。您可以根据需要选择合适的方法进行格式化输出