gdscript_format_string.rst 12 KB

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