gdscript_format_string.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. Placeholder modifiers
  91. ~~~~~~~~~~~~~~~~~~~~~
  92. These characters appear before the above. Some of them work only under certain
  93. conditions.
  94. +---------+-------------------------------------------------------------------+
  95. | ``+`` | In number specifiers, **show + sign** if positive. |
  96. +---------+-------------------------------------------------------------------+
  97. | Integer | Set **padding**. Padded with spaces or with zeroes if integer |
  98. | | starts with ``0`` in an integer placeholder. When used after |
  99. | | ``.``, see ``.``. |
  100. +---------+-------------------------------------------------------------------+
  101. | ``.`` | Before ``f``, set **precision** to 0 decimal places. Can be |
  102. | | followed up with numbers to change. Padded with zeroes. |
  103. +---------+-------------------------------------------------------------------+
  104. | ``-`` | **Pad to the right** rather than the left. |
  105. +---------+-------------------------------------------------------------------+
  106. | ``*`` | **Dynamic padding**, expect additional integral parameter to set |
  107. | | padding or precision after ``.``, see `dynamic padding`_. |
  108. +---------+-------------------------------------------------------------------+
  109. Padding
  110. -------
  111. The ``.`` (*dot*), ``*`` (*asterisk*), ``-`` (*minus sign*) and digit
  112. (``0``-``9``) characters are used for padding. This allows printing several
  113. values aligned vertically as if in a column, provided a fixed-width font is
  114. used.
  115. To pad a string to a minimum length, add an integer to the specifier:
  116. ::
  117. print("%10d" % 12345)
  118. # output: " 12345"
  119. # 5 leading spaces for a total length of 10
  120. If the integer starts with ``0``, integral values are padded with zeroes
  121. instead of white space:
  122. ::
  123. print("%010d" % 12345)
  124. # output: "0000012345"
  125. Precision can be specified for real numbers by adding a ``.`` (*dot*) with an
  126. integer following it. With no integer after ``.``, a precision of 0 is used,
  127. rounding to integral value. The integer to use for padding must appear before
  128. the dot.
  129. ::
  130. # Pad to minimum length of 10, round to 3 decimal places
  131. print("%10.3f" % 10000.5555)
  132. # Output: " 10000.556"
  133. # 1 leading space
  134. The ``-`` character will cause padding to the right rather than the left,
  135. useful for right text alignment:
  136. ::
  137. print("%-10d" % 12345678)
  138. # Output: "12345678 "
  139. # 2 trailing spaces
  140. Dynamic padding
  141. ~~~~~~~~~~~~~~~
  142. By using the ``*`` (*asterisk*) character, the padding or precision can be set
  143. without modifying the format string. It is used in place of an integer in the
  144. format specifier. The values for padding and precision are then passed when
  145. formatting:
  146. ::
  147. var format_string = "%*.*f"
  148. # Pad to length of 7, round to 3 decimal places:
  149. print(format_string % [7, 3, 8.8888])
  150. # Output: " 8.889"
  151. # 2 leading spaces
  152. It is still possible to pad with zeroes in integer placeholders by adding ``0``
  153. before ``*``:
  154. ::
  155. print("%0*d" % [2, 3])
  156. # Output: "03"
  157. Escape sequence
  158. ---------------
  159. To insert a literal ``%`` character into a format string, it must be escaped to
  160. avoid reading it as a placeholder. This is done by doubling the character:
  161. ::
  162. var health = 56
  163. print("Remaining health: %d%%" % health)
  164. # Output: "Remaining health: 56%"
  165. Format method examples
  166. ----------------------
  167. The following are some examples of how to use the various invocations of the
  168. ``String.format`` method.
  169. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  170. | **Type** | **Style** | **Example** | **Result** |
  171. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  172. | Dictionary | key | ``"Hi, {name} v{version}!".format({"name":"Godette", "version":"3.0"})`` | Hi, Godette v3.0! |
  173. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  174. | Dictionary | index | ``"Hi, {0} v{1}!".format({"0":"Godette", "1":"3.0"})`` | Hi, Godette v3.0! |
  175. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  176. | Dictionary | mix | ``"Hi, {0} v{version}!".format({"0":"Godette", "version":"3.0"})`` | Hi, Godette v3.0! |
  177. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  178. | Array | key | ``"Hi, {name} v{version}!".format([["version","3.0"], ["name","Godette"]])`` | Hi, Godette v3.0! |
  179. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  180. | Array | index | ``"Hi, {0} v{1}!".format(["Godette","3.0"])`` | Hi, Godette v3.0! |
  181. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  182. | Array | mix | ``"Hi, {name} v{0}!".format([3.0, ["name","Godette"]])`` | Hi, Godette v3.0! |
  183. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  184. | Array | no index | ``"Hi, {} v{}!".format(["Godette", 3.0], "{}")`` | Hi, Godette v3.0! |
  185. +------------+-----------+------------------------------------------------------------------------------+-------------------+
  186. Placeholders can also be customized when using ``String.format``, here's some
  187. examples of that functionality.
  188. +-----------------+------------------------------------------------------+------------------+
  189. | **Type** | **Example** | **Result** |
  190. +-----------------+------------------------------------------------------+------------------+
  191. | Infix (default) | ``"Hi, {0} v{1}".format(["Godette", "3.0"], "{_}")`` | Hi, Godette v3.0 |
  192. +-----------------+------------------------------------------------------+------------------+
  193. | Postfix | ``"Hi, 0% v1%".format(["Godette", "3.0"], "_%")`` | Hi, Godette v3.0 |
  194. +-----------------+------------------------------------------------------+------------------+
  195. | Prefix | ``"Hi, %0 v%1".format(["Godette", "3.0"], "%_")`` | Hi, Godette v3.0 |
  196. +-----------------+------------------------------------------------------+------------------+
  197. Combining both the ``String.format`` method and the ``%`` operator could be useful, as
  198. ``String.format`` does not have a way to manipulate the representation of numbers.
  199. +---------------------------------------------------------------------------+-------------------+
  200. | **Example** | **Result** |
  201. +---------------------------------------------------------------------------+-------------------+
  202. | ``"Hi, {0} v{version}".format({0:"Godette", "version":"%0.2f" % 3.114})`` | Hi, Godette v3.11 |
  203. +---------------------------------------------------------------------------+-------------------+