format()
메서드는 입력한 값의 형식을 지정합니다.
괄호 {}로 표시된 위치에 지정된 형식의 문자열을 대체합니다.
아래의 예제는 format() 메서드를 사용한 가장 간단한 예제입니다.
**예제1 - 한 개의 인자**
age = 10
string1 = 'I am {} years old.'.format(age)
print(string1)
I am 10 years old.
괄호 {}의 사이에 변수 age의 값인 숫자 10을 대체합니다.
**예제2 - 여러 개의 인자 사용하기**
num_apple = 3
num_banana = 5
string2 = 'There are {} apples and {} bananas'.format(num_apple, num_banana)
print(string2)
여러 개의 숫자를 대체할 수 있습니다.
**예제3 - 숫자로 위치 지정하기**
name = 'Eric'
age = 10
string3 = 'My name is {0}. I am {1} years old.'.format(name, age)
string4 = 'My name is {1}. I am {0} years old.'.format(name, age)
print(string3)
print(string4)
My name is Eric. I am 10 years old.
My name is 10. I am Eric years old.
괄호 안에 숫자를 입력하면 format() 메서드에 전달된 객체의 위치를 지정할 수 있습니다.
위의 예제에서 {0}에는 name의 값, {1}에는 age의 값이 대체됩니다.
**예제4 - 키워드로 위치 지정하기**
string5 = 'My name is {name}. I am {age} years old.'.format(name='Eric', age=10)
print(string5)
My name is Eric. I am 10 years old.
format() 메서드에 키워드 인자를 사용해서, 위치를 더 명확하게 지정할 수도 있습니다.
**형식 지정하기**
**예제1 - 숫자 기본 형식**
# Fixed point number format
amount1 = 123456
print('{:f}'.format(amount1))
print('{:.2f}'.format(amount1))
# Decimal format
amount2 = 0b0101
print('{:d}'.format(amount2))
# Binary format
amount3 = 5
print('{:b}'.format(amount3))
# Scientific format
amount4 = 321000
print('{:E}'.format(amount4))
print('{:e}'.format(amount4))
print('{:.2e}'.format(amount4))
123456.000000
123456.00
5
101
3.210000E+05
3.210000e+05
3.21e+05
:f
는 고정소수점 형식 (fixed point number format)을 지정합니다.
:.2f
는 소수점 아래 둘째 자리까지 표시합니다. (디폴트는 소수점 아래 여섯자리)
:d
는 숫자를 십진수 (decimal format)로 표현합니다.
:b
는 숫자를 이진수 (binary format)로 표현합니다.
:E
는 숫자를 과학적 기수법 (scientific format)으로 표현합니다. :e
와 같이 설정하면 소문자 e로 나타냅니다.
:.2e
와 같이 소수점 형식을 지정할 수 있습니다.
**예제2 - 화폐 형식 (천 단위 구분자)**
# Thousand separator
amount1 = 123456
amount2 = 123456.78
print('${:,}'.format(amount1))
print('€{:,}'.format(amount2))
$123,456
€123,456.78
숫자를 화폐 단위로 표현하기 위해서 :,
와 같이 형식을 지정하면 천 단위마다 콤마 (comma)를 표시합니다.
**예제3 - 백분율 형식**
# Percentage format
perc1 = 0.003
perc2 = 0.68
perc3 = 0.261387
print('{:%}'.format(perc1))
print('{:.1%}'.format(perc2))
print('{:.3%}'.format(perc3))
0.300000%
68.0%
26.139%
숫자를 백분율 형식으로 표현하기 위해 :%
와 같이 지정할 수 있습니다.
앞의 예제에서와 마찬가지로 :.1%
, :.3%
와 같이 소수점 형식을 지정할 수 있습니다.
**예제4 - 부호 표현**
# Plus sign if positive
a = 123
b = 0
c = -123
print('{:+}/{:+}/{:+}'.format(a, b, c))
+123/+0/-123
:+
는 숫자가 음이 아닌 경우에 + 부호를 표현합니다.
또 다른 예시
# 진수 변환
>> bin(30)
'0b1110'
>> oct(30)
'0o36'
>> hex(30)
'0x1e'
format 함수
# 접두어 제외하기
>> format(0b11110, 'b')
'11110'
# 접두어 포함
>> format(30, '#b')
'11110'