如何在python中打印C格式

KTr*_*ran 1 python printf string-formatting

一个python新手问题:

我想用带有参数列表的 c 格式在 python 中打印:

agrs = [1,2,3,"hello"]
string = "This is a test %d, %d, %d, %s"
Run Code Online (Sandbox Code Playgroud)

如何使用 python 打印:

这是一个测试 1, 2, 3, 你好

谢谢。

Sha*_*ger 6

字符串会重载模数运算符 ,%用于printf-style 格式化,以及tuple使用多个值进行格式化的特殊情况 s ,因此您需要做的就是从 转换listtuple

print(string % tuple(agrs))
Run Code Online (Sandbox Code Playgroud)


elf*_*elf 5

元组:

例子:

print("Total score for %s is %s  " % (name, score))
Run Code Online (Sandbox Code Playgroud)

在你的情况下:

print(string % tuple(agrs))
Run Code Online (Sandbox Code Playgroud)

或者使用新样式的字符串格式:

print("Total score for {} is {}".format(name, score))
Run Code Online (Sandbox Code Playgroud)

或者将值作为参数传递并打印将执行此操作:

print("Total score for", name, "is", score)
Run Code Online (Sandbox Code Playgroud)

来源