Skip to content

str.format()

% 기호를 사용하는 대신 형식을 지정할 곳에 {}기호를 사용한다. % 기호처럼 자료형을 선언할 필요가 없다.

python
name = "홍길동"
age = 17
score = 91.35
print("이름: {}, 나이: {}, 점수: {}".format(name, age, score))
print("이름: {1}, 나이: {2}, 점수: {0}".format(score, name, age))
plaintext
이름: 홍길동, 나이: 17, 점수: 91.35
이름: 홍길동, 나이: 17, 점수: 91.35

{}안에 순서를 생략할 경우 format()에 작성한 차례대로 출력된다. 가장 앞에 있는 값은 {0}부터 시작한다.

%10s처럼 출력할 글자수를 지정하기 위해 다음과 같이 설정할 수 있다.

형식 지정내용
{:>10}전체 10칸을 차지하며 공백을 앞에 붙임
{:<10}전체 10칸을 차지하며 공백을 뒤에 붙임
{:^10}전체 10칸을 차지하며 문자열을 중앙에 출력
{:.3f}소수점 아래 3자리까지 표시
{:,}천단위 쉼표를 출력
python
name = "홍길동"
score = 91.35
print("[{:>10}]".format(name))
print("[{:<10}]".format(name))
print("[{:^10}]".format(name))
print("[{:.5f}]".format(score))
print("[{:8.3f}]".format(score))
print("[{:<8.3f}]".format(score))
print("[{:>8.3f}]".format(score))
print("[{:,}]".format(1230000))
plaintext
[       홍길동]
[홍길동       ]
[   홍길동    ]
[91.35000]
[  91.350]
[91.350  ]
[  91.350]
[1,230,000]

> 기호 앞에 문자열을 쓰면 공백을 해당 문자열로 채워 준다.

python
name = "홍길동"
print("[{:*>10}]".format(name))
print("[{:#<10}]".format(name))
print("[{:?^10}]".format(name))
plaintext
[*******홍길동]
[홍길동#######]
[???홍길동????]

format 메서드는 다음과 같이 분리한 후에도 사용이 가능하다.

python
name = "홍길동"
age = 17
score = 91.35
temp = "이름: {}, 나이: {}, 점수: {}"
temp = temp.format(name, age, score)
print(temp)
plaintext
이름: 홍길동, 나이: 17, 점수: 91.35

Powered by vitepress-logo-mini