파이썬 문자열 format() 메서드
예시
자리 표시자 안에 가격을 삽입하십시오. 가격은 고정 소수점 형식이어야 합니다.
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
정의 및 사용
이 format()
메서드는 지정된 값의 형식을 지정하고 문자열의 자리 표시자 안에 삽입합니다.
자리 표시자는 중괄호({})를 사용하여 정의됩니다. 아래 자리 표시자 섹션에서 자리 표시자에 대해 자세히 알아보세요.
이 format()
메서드는 형식이 지정된 문자열을 반환합니다.
통사론
string.format(value1, value2...)
매개변수 값
Parameter | Description |
---|---|
value1, value2... | Required. One or more values that should be formatted and inserted in
the string. The values are either a list of values separated by commas, a key=value list, or a combination of both. The values can be of any data type. |
자리 표시자
{price}
자리 표시자는 명명된 인덱스 , 번호가 지정된 인덱스 {0}
또는 빈 자리 표시자를
사용하여 식별할 수 있습니다
{}
.
예시
다른 자리 표시자 값 사용:
txt1 = "My
name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My
name is {0}, I'm {1}".format("John",36)
txt3 = "My
name is {}, I'm {}".format("John",36)
서식 유형
자리 표시자 내에서 형식 지정 유형을 추가하여 결과 형식을 지정할 수 있습니다.
:< |
Left aligns the result (within the available space) | |
:> |
Right aligns the result (within the available space) | |
:^ |
Center aligns the result (within the available space) | |
:= |
Places the sign to the left most position | |
:+ |
Use a plus sign to indicate if the result is positive or negative | |
:- |
Use a minus sign for negative values only | |
: |
Use a space to insert an extra space before positive numbers (and a minus sign before negative numbers) | |
:, |
Use a comma as a thousand separator | |
:_ |
Use a underscore as a thousand separator | |
:b |
Binary format | |
:c |
Converts the value into the corresponding unicode character | |
:d |
Decimal format | |
:e |
Scientific format, with a lower case e | |
:E |
Scientific format, with an upper case E | |
:f |
Fix point number format | |
:F |
Fix point number format, in uppercase format (show
inf and
nan as INF
and NAN ) |
|
:g |
General format | |
:G |
General format (using a upper case E for scientific notations) | |
:o |
Octal format | |
:x |
Hex format, lower case | |
:X |
Hex format, upper case | |
:n |
Number format | |
:% |
Percentage format |