打印日志 (print)

4.6 2026-01-27

开发中,主要通过print打印日志,编辑器中可以通过输出面板查看。发布游戏后,可以通过控制台查看日志。


print("hello")

print("hello ", "John ", "Doe")

print("hello " + "John " + "Doe")

print("hello {0} {1}".format(["John", Doe]))

print("hello %s %s" % ("John", "Doe"))

s 字符串

c Unicode字符串

d 十进制整型

o 八进制整型

x 十六进制,字母小写

X 十六进制,字母大写

f 浮点小数

v 向量 Vector2, Vector3, Vector4, Vector2i, Vector3i, Vector4i

补齐


# 输出 "     12345" 总长度10,前方补齐5个空格
print("%10d" % 12345)

# 输出 "0000012345" 总长度10,前方补齐5个0
print("%010d" % 12345)

# 输出 " 10000.556" 总长度10,前方补齐1个空格,保留3位小数,四舍五入
print("%10.3f" % 10000.5555)

# 输出 "12345678  " 总长度10,后方补齐2个空格
print("%-10d" % 12345678)

# 输出 "  8.889" 总长度7,前方补齐2个空格,保留3位小数,四舍五入
print("%*.*f" % [7, 3, 8.888])

# 输出 “03” 总长度2,前方补齐1个0
print("%0*d" % [2, 3])

转义字符

连续两个%,输出一个%。


# 输出 "hello : 100%"
print("hello : %d%%" % 100)

格式化方法


# 输出 "hello : Godot"
print("hello : {str}".format({"str": "Godot"}))

Dictionary (key) "Hi, {name} v{version}".format({"name": "Godot", "version": "4.0"})

Dictionary (index) "Hi, {0} v{1}".format({"0": "Godot", "1": "4.0"}

Array (key) "Hi, {name} v{version}".format([["version": "4.0", "name": "Godot"]])

Array (index) "Hi, {0} v{1}".format(["Godot", "4.0"])

Array (mix) "Hi, {name} v{0}".format(["4.0", ["name", "Godot"]])

Array (no index) "Hi, {} v{}".format(["Godot", "4.0"], "{}")

自定义占位符

Infix (default) "Hi, {0} v{1}".format(["Godot", "4.0"], "{_}")

后缀 "Hi, 0% v1%}".format(["Godot", "4.0"], "_%")

前缀 "Hi, %0 v%1".format(["Godot", "4.0"], "%_")