Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
GDScript 형식 문자열(format strings)
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 {} 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.
많은 플레이스 홀더
형식 문자열은 여러가지 플레이스 홀더를 가질 수 있습니다. 예를 들어, 값은 배열의 형식으로, 각각의 플레이스 홀더에 단일 값으로 전달됩니다 (*
으로 이루어진 형식 지정자를 사용하지 않는다면, 동적 패딩 을 참고하세요):
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."
값은 순서대로 삽입됩니다. 모든 플레이스 홀더는 한번에 바꾸어야 하기 때문에, 적절한 수의 값이 있어야 합니다.
형식 지정자(Format specifiers)
플레이스 홀더에 사용되는 s
이외에도 다른 형식 지정자가 있습니다. 이들은 하나 이상의 문자로 구성됩니다. s
처럼 스스로 작동하는 것이 있는 반면, 일부는 다른 문자 앞에 나타나기도 하며, 어떤 것은 오직 특정 값이나 문자에만 작동합니다.
플레이스 홀더 유형
이들 중 하나가 반드시 형식 지정자의 마지막 문자로 항상 나타나야 합니다. s
와는 별개로, 이들은 특정 타입의 매개변수가 필요합니다.
|
암시적 문자열 변환과 같은 방법으로 문자열을 간단히 변환합니다. |
|
하나의 유니코드 문자. 코드 포인트나 단일 문자의 경우 부호가 없는 8비트 정수 (0-255) 가 필요합니다. |
|
A decimal integer. Expects an integer or a real number (will be floored). |
|
An octal integer. Expects an integer or a real number (will be floored). |
|
A hexadecimal integer with lower-case letters. Expects an integer or a real number (will be floored). |
|
A hexadecimal integer with upper-case letters. Expects an integer or a real number (will be floored). |
|
A decimal real number. Expects an integer or a real number. |
|
A vector. Expects any float or int-based vector object (
|
플레이스 홀더 수정자
이 문자는 위 문자들보다 앞에서 나타납니다. 일부는 특정 조건에서만 작동합니다.
|
숫자 지정자에서, 숫자가 양수라면 + 부호를 표시합니다. |
정수(Integer) |
Set padding. Padded with spaces or with zeroes if integer
starts with |
|
Before |
|
왼쪽 대신 오른쪽을 채웁니다. |
|
Dynamic padding, expects additional integer parameter to set
padding or precision after |
패딩
.
(점), *
(별표), -
(빼기 문자) 그리고 한 자리 수 (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"
이스케이프 시퀀스
상수 %
문자를 형식 문자열에 넣으려면, 플레이스 홀더처럼 읽히지 않도록 이스케이프 해야 합니다. 잘못하면 문자를 두 배로 만들 것입니다:
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.
유형 |
스타일 |
예제 |
결과 |
딕셔너리 |
키 |
|
안녕, Godette v3.0! |
딕셔너리 |
인덱스 |
|
안녕, Godette v3.0! |
딕셔너리 |
믹스 |
|
안녕, Godette v3.0! |
배열 |
키 |
|
안녕, Godette v3.0! |
배열 |
인덱스 |
|
안녕, Godette v3.0! |
배열 |
믹스 |
|
안녕, Godette v3.0! |
배열 |
인덱스 없음 |
|
안녕, Godette v3.0! |
플레이스 홀더도 ``String.format``을 사용할 때 사용자 정의를 할 수 있습니다, 이 기능의 몇 가지 예를 소개합니다.
유형 |
예제 |
결과 |
중위 (기본) |
|
안녕, Godette v3.0 |
후위 |
|
안녕, Godette v3.0 |
접두사 |
|
안녕, Godette v3.0 |
String.format
메서드와 %
연산자를 결합함으로써 String.format
이 다룰 수 없는 숫자 표현을 다룰 수 있게 됩니다.
예제 |
결과 |
|
안녕, 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.