GDScriptフォーマット文字列

Godot offers multiple ways to dynamically change the contents of strings:

  • Format strings: var string = "I have %s cats." % "3"

  • The String.format() method: var string = "I have {0} cats.".format([3])

  • String concatenation: var string = "I have " + str(3) + " cats."

This page explains how to use format strings, and briefly explains the format() method and string concatenation.

Format strings

Format strings are a way to reuse text templates to succinctly create different but similar strings.

Format strings are just like normal strings, except they contain certain placeholder character sequences such as %s. These placeholders can then be replaced by parameters handed to the format string.

具体的なGDScriptの例を見てみましょう:

# Define a format string with placeholder '%s'
var format_string = "We're waiting for %s."

# Using the '%' operator, the placeholder is replaced with the desired value
var actual_string = format_string % "Godot"

print(actual_string)
# Output: "We're waiting for Godot."

プレースホルダは常に % で始まりますが、次の文字(format specifier)は、指定された値を文字列に変換する方法を決定します。

The %s seen in the example above is the simplest placeholder and works for most use cases: it converts the value by the same method by which an implicit String conversion or str() would convert it. Strings remain unchanged, booleans turn into either "True" or "False", an int or float becomes a decimal, and other types usually return their data in a human-readable string.

There are other format specifiers.

複数のプレースホルダ

フォーマット文字列には複数のプレースホルダを含めることができます。そのような場合、値は配列の形で渡され、プレースホルダごとに1つの値になります( * でフォーマット指定子を使用しない限り。 動的パディング を参照):

var format_string = "%s was reluctant to learn %s, but now he enjoys it."
var actual_string = format_string % ["Estragon", "GDScript"]

print(actual_string)
# Output: "Estragon was reluctant to learn GDScript, but now he enjoys it."

値が順番に挿入されていることに注意してください。すべてのプレースホルダは一度に置き換えられる必要があるので、適切な数の値が必要です。

書式指定子

プレースホルダで使用できる書式指定子は、 s 以外にもあります。これらは1つ以上の文字で構成されます。その中には、 s のように単独で動作するものもあれば、他の文字の前に現れるものもあり、特定の値や文字だけで動作するものもあります。

プレースホルダ・タイプ

これらのうちの1つだけが、常にフォーマット指定子の最後の文字として表示されている必要があります。 s とは別に、これらは特定の種類のパラメーターを必要とします。

s

暗黙的な文字列変換と同じメソッドによる文字列への単純な変換。

c

単一のUnicode文字。 コードポイントまたは1文字の文字列には、符号なし8ビット整数(0〜255)が必要です。

d

A decimal integer. Expects an integer or a real number (will be floored).

o

An octal integer. Expects an integer or a real number (will be floored).

x

A hexadecimal integer with lower-case letters. Expects an integer or a real number (will be floored).

x

A hexadecimal integer with upper-case letters. Expects an integer or a real number (will be floored).

f

A decimal real number. Expects an integer or a real number.

v

単一の**ベクトル**。 float または int ベースのベクトル オブジェクト ( Vector2Vector3Vector4Vector2iVector3iVector4i) を指定します。ベクトルの座標を括弧内に表示し、各座標を %f であるかのようにフォーマットし同じ修飾子を使用します。

プレースホルダ修飾子

これらの文字は上記の前に表示されます。中には、特定の条件下でのみ機能するものもあります。

+

数値指定子で、正の場合は+記号を表示します。

整数

パディングを設定します。 整数または実数のプレースホルダ内で整数が 0 で始まる場合は、スペースまたはゼロでパディングされます。 - が存在する場合、先頭の「0」は無視されます。後に . を使用する場合は、. を参照してください。

.

f または v の前に 、精度を小数点以下0桁に設定します。 変更する数字でフォローアップすることができます。 ゼロでパディングされます。

-

左ではなく右にパディングされます。

*

Dynamic padding, expects additional integer parameter to set padding or precision after ., see dynamic padding.

パディング

. (ドット), * (アスタリスク), - (マイナス記号) および数字 (0-9) の文字が埋め込みに使用されます。これにより、固定幅フォントが使用されている場合に、縦に並んだ複数の値を列のように出力できます。

文字列を最小の長さにするには、指定子に整数を追加します:

print("%10d" % 12345)
# output: "     12345"
# 5 leading spaces for a total length of 10

If the integer starts with 0, integer values are padded with zeroes instead of white space:

print("%010d" % 12345)
# output: "0000012345"

Precision can be specified for real numbers by adding a . (dot) with an integer following it. With no integer after ., a precision of 0 is used, rounding to integer values. The integer to use for padding must appear before the dot.

# Pad to minimum length of 10, round to 3 decimal places
print("%10.3f" % 10000.5555)
# Output: " 10000.556"
# 1 leading space

- 文字を使用すると、左ではなく右にスペースが挿入され、テキストの右揃えに便利です:

print("%-10d" % 12345678)
# Output: "12345678  "
# 2 trailing spaces

動的パディング

* (アスタリスク)文字を使用すると、フォーマット文字列を変更せずにパディングまたは精度を設定できます。フォーマット指定子の整数の代わりに使用されます。 フォーマット時にパディングと精度の値が渡されます:

var format_string = "%*.*f"
# Pad to length of 7, round to 3 decimal places:
print(format_string % [7, 3, 8.8888])
# Output: "  8.889"
# 2 leading spaces

* の前に 0 を追加することで、整数のプレースホルダに0を埋め込むこともできます:

print("%0*d" % [2, 3])
# Output: "03"

エスケープシーケンス

フォーマット文字列にリテラルの % 文字を挿入するには、プレースホルダとして読み取られないようにエスケープする必要があります。これは文字を2倍にすることによって行われます:

var health = 56
print("Remaining health: %d%%" % health)
# Output: "Remaining health: 56%"

String format method

There is also another way to format text in GDScript, namely the String.format() method. It replaces all occurrences of a key in the string with the corresponding value. The method can handle arrays or dictionaries for the key/value pairs.

配列はキー、インデックス、または混合スタイルとして使用できます(下記の例を参照)。配列のインデックスまたは混合スタイルが使用されている場合にのみ順序が重要になります。

GDScriptの簡単な例:

# Define a format string
var format_string = "We're waiting for {str}"

# Using the 'format' method, replace the 'str' placeholder
var actual_string = format_string.format({"str": "Godot"})

print(actual_string)
# Output: "We're waiting for Godot"

フォーマット方法の例

The following are some examples of how to use the various invocations of the String.format() method.

様式

結果

辞書(ディクショナリ)

キー

"やあ、 {name} v{version}!".format({"name":"Godette", "version":"3.0"})

やあ、 Godette v3.0!

辞書(ディクショナリ)

インデックス

"やあ、 {0} v{1}!".format({"0":"Godette", "1":"3.0"})

やあ、 Godette v3.0!

辞書(ディクショナリ)

キーとインデックス

"やあ、 {0} v{version}!".format({"0":"Godette", "version":"3.0"})

やあ、 Godette v3.0!

配列

キー

"やあ、 {name} v{version}!".format([["version","3.0"], ["name","Godette"]])

やあ、 Godette v3.0!

配列

インデックス

"やあ、 {0} v{1}!".format(["Godette","3.0"])

やあ、 Godette v3.0!

配列

キーとインデックス

"Hi, {name} v{0}!".format(["3.0", ["name","Godette"]])

やあ、 Godette v3.0!

配列

インデックスなし

"Hi, {} v{}!".format(["Godette", "3.0"], "{}")

やあ、 Godette v3.0!

String.format を使用するときにプレースホルダをカスタマイズすることもできます。これはその機能の例です。

結果

インフィックス(デフォルト)

"やあ、 {0} v{1}".format(["Godette", "3.0"], "{_}")

やあ、 Godette v3.0

ポストフィックス

"やあ、 0% v1%".format(["Godette", "3.0"], "_%")

やあ、 Godette v3.0

折り返しの接頭辞:

"やあ、 %0 v%1".format(["Godette", "3.0"], "%_")

やあ、 Godette v3.0

String.format には数値の表現を操作する方法がないため、String.format メソッドと % 演算子の両方を組み合わせると便利です。

結果

"やあ、 {0} v{version}".format({0:"Godette", "version":"%0.2f" % 3.114})

やあ、 Godette v3.11

String concatenation

You can also combine strings by concatenating them together, using the + operator.

# Define a base string
var base_string = "We're waiting for "

# Concatenate the string
var actual_string = base_string + "Godot"

print(actual_string)
# Output: "We're waiting for Godot"

When using string concatenation, values that are not strings must be converted using the str() function. There is no way to specify the string format of converted values.

var name_string = "Godette"
var version = 3.0
var actual_string = "Hi, " + name_string + " v" + str(version) + "!"

print(actual_string)
# Output: "Hi, Godette v3!"

Because of these limitations, format strings or the format() method are often a better choice. In many cases, string concatenation is also less readable.

注釈

In Godot's C++ code, GDScript format strings can be accessed using the vformat() helper function in the Variant header.