gdscript_format_string.rst 13 KB

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