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, 你好
谢谢。
字符串会重载模数运算符 ,%用于printf-style 格式化,以及tuple使用多个值进行格式化的特殊情况 s ,因此您需要做的就是从 转换list为tuple:
print(string % tuple(agrs))
Run Code Online (Sandbox Code Playgroud)
元组:
例子:
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)
| 归档时间: |
|
| 查看次数: |
6108 次 |
| 最近记录: |