4.9.4. 문자열 포맷 연산자

문자열 포맷 연산자 % 는 C의 printf() 함수와 비슷합니다. 일정한 포맷에 맞춰 문자열을 조합하는 것을 문자열 포맷팅이라 합니다.

print "My name is %s and weight is %d kg!" % ('Zara', 21)

위의 코드가 실행 되면 다음과 같은 결과를 출력 합니다.

My name is Zara and weight is 21 kg!

다음은 % 와 함께 사용할 수 있는 변환 지시어 입니다.

Format Symbol

Conversion

%c

character

%s

string conversion via str() prior to formatting

%i

signed decimal integer

%d

signed decimal integer

%u

unsigned decimal integer

%o

octal integer

%x

hexadecimal integer (lowercase letters)

%X

hexadecimal integer (UPPERcase letters)

%e

exponential notation (with lowercase 'e')

%E

exponential notation (with UPPERcase 'E')

%f

floating point real number

%g

the shorter of %f and %e

%G

the shorter of %f and %E

기타 지원되는 기호 및 기능은 다음 표에 나열되어 있습니다.

Symbol

Functionality

*

argument specifies width or precision

-

left justification

+

display the sign

<sp>

leave a blank space before a positive number

#

add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.

0

pad from left with zeros (instead of spaces)

%

'%%' leaves you with a single literal '%'

(var)

mapping variable (dictionary arguments)

m.n.

m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

format 함수는 문자를 다양한 형태로 포맷팅하는데 사용합니다. 위치를 기준으로 하는 인덱스형, 필드명을 기준으로 하는 키워드형, 리스트 인덱스형으로 사용할 수 있습니다.

Last updated

Was this helpful?