gdscript_format_string.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. .. _doc_gdscript_printf:
  2. GDScript format strings
  3. =======================
  4. Godot offers multiple ways to dynamically change the contents of strings:
  5. - Format strings: ``var string = "I have %s cats." % "3"``
  6. - The ``String.format()`` method: ``var string = "I have {} cats.".format([3])``
  7. - String concatenation: ``var string = "I have " + str(3) + " cats."``
  8. This page explains how to use format strings, and briefly explains the ``format()``
  9. method and string concatenation.
  10. Format strings
  11. --------------
  12. *Format strings* are a way to reuse text templates to succinctly create different
  13. but similar strings.
  14. Format strings are just like normal strings, except they contain certain
  15. placeholder character sequences such as ``%s``. These placeholders can then
  16. be replaced by parameters handed to the format string.
  17. Examine this concrete GDScript example:
  18. ::
  19. # Define a format string with placeholder '%s'
  20. var format_string = "We're waiting for %s."
  21. # Using the '%' operator, the placeholder is replaced with the desired value
  22. var actual_string = format_string % "Godot"
  23. print(actual_string)
  24. # Output: "We're waiting for Godot."
  25. Placeholders always start with a ``%``, but the next character or characters,
  26. the *format specifier*, determines how the given value is converted to a
  27. string.
  28. The ``%s`` seen in the example above is the simplest placeholder and works for
  29. most use cases: it converts the value by the same method by which an implicit
  30. String conversion or :ref:`str() <class_@GlobalScope_method_str>` would convert
  31. it. Strings remain unchanged, booleans turn into either ``"True"`` or ``"False"``,
  32. an ``int`` or ``float`` becomes a decimal, and other types usually return their data
  33. in a human-readable string.
  34. There are other `format specifiers`_.
  35. Multiple placeholders
  36. ---------------------
  37. Format strings may contain multiple placeholders. In such a case, the values
  38. are handed in the form of an array, one value per placeholder (unless using a
  39. format specifier with ``*``, see `dynamic padding`_):
  40. ::
  41. var format_string = "%s was reluctant to learn %s, but now he enjoys it."
  42. var actual_string = format_string % ["Estragon", "GDScript"]
  43. print(actual_string)
  44. # Output: "Estragon was reluctant to learn GDScript, but now he enjoys it."
  45. Note the values are inserted in order. Remember all placeholders must be
  46. replaced at once, so there must be an appropriate number of values.
  47. Format specifiers
  48. -----------------
  49. There are format specifiers other than ``s`` that can be used in placeholders.
  50. They consist of one or more characters. Some of them work by themselves like
  51. ``s``, some appear before other characters, some only work with certain
  52. values or characters.
  53. Placeholder types
  54. ~~~~~~~~~~~~~~~~~
  55. One and only one of these must always appear as the last character in a format
  56. specifier. Apart from ``s``, these require certain types of parameters.
  57. +-------+---------------------------------------------------------------------+
  58. | ``s`` | **Simple** conversion to String by the same method as implicit |
  59. | | String conversion. |
  60. +-------+---------------------------------------------------------------------+
  61. | ``c`` | A single **Unicode character**. Expects an unsigned 8-bit integer |
  62. | | (0-255) for a code point or a single-character string. |
  63. +-------+---------------------------------------------------------------------+
  64. | ``d`` | A **decimal integer**. Expects an integer or a real number |
  65. | | (will be floored). |
  66. +-------+---------------------------------------------------------------------+
  67. | ``o`` | An **octal integer**. Expects an integer or a real number |
  68. | | (will be floored). |
  69. +-------+---------------------------------------------------------------------+
  70. | ``x`` | A **hexadecimal integer** with **lower-case** letters. |
  71. | | Expects an integer or a real number (will be floored). |
  72. +-------+---------------------------------------------------------------------+
  73. | ``X`` | A **hexadecimal integer** with **upper-case** letters. |
  74. | | Expects an integer or a real number (will be floored). |
  75. +-------+---------------------------------------------------------------------+
  76. | ``f`` | A **decimal real** number. Expects an integer or a real number. |
  77. +-------+---------------------------------------------------------------------+
  78. | ``v`` | A **vector**. Expects any float or int-based vector object ( |
  79. | | ``Vector2``, ``Vector3``, ``Vector4``, ``Vector2i``, ``Vector3i`` or|
  80. | | ``Vector4i``). Will display the vector coordinates in parentheses, |
  81. | | formatting each coordinate as if it was an ``%f``, and using the |
  82. | | same modifiers. |
  83. +-------+---------------------------------------------------------------------+
  84. Placeholder modifiers
  85. ~~~~~~~~~~~~~~~~~~~~~
  86. These characters appear before the above. Some of them work only under certain
  87. conditions.
  88. +---------+-------------------------------------------------------------------+
  89. | ``+`` | In number specifiers, **show + sign** if positive. |
  90. +---------+-------------------------------------------------------------------+
  91. | Integer | Set **padding**. Padded with spaces or with zeroes if integer |
  92. | | starts with ``0`` in an integer or real number placeholder. |
  93. | | The leading ``0`` is ignored if ``-`` is present. |
  94. | | When used after ``.``, see ``.``. |
  95. +---------+-------------------------------------------------------------------+
  96. | ``.`` | Before ``f`` or ``v``, set **precision** to 0 decimal places. Can |
  97. | | be followed up with numbers to change. Padded with zeroes. |
  98. +---------+-------------------------------------------------------------------+
  99. | ``-`` | **Pad to the right** rather than the left. |
  100. +---------+-------------------------------------------------------------------+
  101. | ``*`` | **Dynamic padding**, expects additional integer parameter to set |
  102. | | padding or precision after ``.``, see `dynamic padding`_. |
  103. +---------+-------------------------------------------------------------------+
  104. Padding
  105. -------
  106. The ``.`` (*dot*), ``*`` (*asterisk*), ``-`` (*minus sign*) and digit
  107. (``0``-``9``) characters are used for padding. This allows printing several
  108. values aligned vertically as if in a column, provided a fixed-width font is
  109. used.
  110. To pad a string to a minimum length, add an integer to the specifier:
  111. ::
  112. print("%10d" % 12345)
  113. # output: " 12345"
  114. # 5 leading spaces for a total length of 10
  115. If the integer starts with ``0``, integer values are padded with zeroes
  116. instead of white space:
  117. ::
  118. print("%010d" % 12345)
  119. # output: "0000012345"
  120. Precision can be specified for real numbers by adding a ``.`` (*dot*) with an
  121. integer following it. With no integer after ``.``, a precision of 0 is used,
  122. rounding to integer values. The integer to use for padding must appear before
  123. the dot.
  124. ::
  125. # Pad to minimum length of 10, round to 3 decimal places
  126. print("%10.3f" % 10000.5555)
  127. # Output: " 10000.556"
  128. # 1 leading space
  129. The ``-`` character will cause padding to the right rather than the left,
  130. useful for right text alignment:
  131. ::
  132. print("%-10d" % 12345678)
  133. # Output: "12345678 "
  134. # 2 trailing spaces
  135. Dynamic padding
  136. ~~~~~~~~~~~~~~~
  137. By using the ``*`` (*asterisk*) character, the padding or precision can be set
  138. without modifying the format string. It is used in place of an integer in the
  139. format specifier. The values for padding and precision are then passed when
  140. formatting:
  141. ::
  142. var format_string = "%*.*f"
  143. # Pad to length of 7, round to 3 decimal places:
  144. print(format_string % [7, 3, 8.8888])
  145. # Output: " 8.889"
  146. # 2 leading spaces
  147. It is still possible to pad with zeroes in integer placeholders by adding ``0``
  148. before ``*``:
  149. ::
  150. print("%0*d" % [2, 3])
  151. # Output: "03"
  152. Escape sequence
  153. ---------------
  154. To insert a literal ``%`` character into a format string, it must be escaped to
  155. avoid reading it as a placeholder. This is done by doubling the character:
  156. ::
  157. var health = 56
  158. print("Remaining health: %d%%" % health)
  159. # Output: "Remaining health: 56%"
  160. String format method
  161. --------------------
  162. There is also another way to format text in GDScript, namely the
  163. :ref:`String.format() <class_String_method_format>`
  164. method. It replaces all occurrences of a key in the string with the corresponding
  165. value. The method can handle arrays or dictionaries for the key/value pairs.
  166. Arrays can be used as key, index, or mixed style (see below examples). Order only
  167. matters when the index or mixed style of Array is used.
  168. A quick example in GDScript:
  169. ::
  170. # Define a format string
  171. var format_string = "We're waiting for {str}"
  172. # Using the 'format' method, replace the 'str' placeholder
  173. var actual_string = format_string.format({"str": "Godot"})
  174. print(actual_string)
  175. # Output: "We're waiting for Godot"
  176. Format method examples
  177. ~~~~~~~~~~~~~~~~~~~~~~
  178. The following are some examples of how to use the various invocations of the
  179. ``String.format()`` method.
  180. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  181. | **Type** | **Style** | **Example** | **Result** |
  182. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  183. | Dictionary | key | ``"Hi, {name} v{version}!".format({"name":"Godette", "version":"3.0"})`` | Hi, Godette v3.0! |
  184. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  185. | Dictionary | index | ``"Hi, {0} v{1}!".format({"0":"Godette", "1":"3.0"})`` | Hi, Godette v3.0! |
  186. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  187. | Dictionary | mix | ``"Hi, {0} v{version}!".format({"0":"Godette", "version":"3.0"})`` | Hi, Godette v3.0! |
  188. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  189. | Array | key | ``"Hi, {name} v{version}!".format([["version","3.0"], ["name","Godette"]])`` | Hi, Godette v3.0! |
  190. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  191. | Array | index | ``"Hi, {0} v{1}!".format(["Godette","3.0"])`` | Hi, Godette v3.0! |
  192. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  193. | Array | mix | ``"Hi, {name} v{0}!".format(["3.0", ["name","Godette"]])`` | Hi, Godette v3.0! |
  194. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  195. | Array | no index | ``"Hi, {} v{}!".format(["Godette", "3.0"], "{}")`` | Hi, Godette v3.0! |
  196. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  197. Placeholders can also be customized when using ``String.format``, here's some
  198. examples of that functionality.
  199. +-----------------+------------------------------------------------------+------------------+
  200. | **Type** | **Example** | **Result** |
  201. +-----------------+------------------------------------------------------+------------------+
  202. | Infix (default) | ``"Hi, {0} v{1}".format(["Godette", "3.0"], "{_}")`` | Hi, Godette v3.0 |
  203. +-----------------+------------------------------------------------------+------------------+
  204. | Postfix | ``"Hi, 0% v1%".format(["Godette", "3.0"], "_%")`` | Hi, Godette v3.0 |
  205. +-----------------+------------------------------------------------------+------------------+
  206. | Prefix | ``"Hi, %0 v%1".format(["Godette", "3.0"], "%_")`` | Hi, Godette v3.0 |
  207. +-----------------+------------------------------------------------------+------------------+
  208. Combining both the ``String.format`` method and the ``%`` operator could be useful, as
  209. ``String.format`` does not have a way to manipulate the representation of numbers.
  210. +---------------------------------------------------------------------------+-------------------+
  211. | **Example** | **Result** |
  212. +---------------------------------------------------------------------------+-------------------+
  213. | ``"Hi, {0} v{version}".format({0:"Godette", "version":"%0.2f" % 3.114})`` | Hi, Godette v3.11 |
  214. +---------------------------------------------------------------------------+-------------------+
  215. String concatenation
  216. --------------------
  217. You can also combine strings by *concatenating* them together, using the ``+``
  218. operator.
  219. ::
  220. # Define a base string
  221. var base_string = "We're waiting for "
  222. # Concatenate the string
  223. var actual_string = base_string + "Godot"
  224. print(actual_string)
  225. # Output: "We're waiting for Godot"
  226. When using string concatenation, values that are not strings must be converted using
  227. the ``str()`` function. There is no way to specify the string format of converted
  228. values.
  229. ::
  230. var name_string = "Godette"
  231. var version = 3.0
  232. var actual_string = "Hi, " + name_string + " v" + str(version) + "!"
  233. print(actual_string)
  234. # Output: "Hi, Godette v3!"
  235. Because of these limitations, format strings or the ``format()`` method are often
  236. a better choice. In many cases, string concatenation is also less readable.
  237. .. note::
  238. In Godot's C++ code, GDScript format strings can be accessed using the
  239. ``vformat()`` helper function in the :ref:`Variant<class_Variant>` header.