본문 바로가기
프로그래밍 언어/Python

파이썬 문자열 출력 포맷팅 방법 f-string, str.format(), %

by pagehit 2022. 1. 8.
반응형

파이썬(Python)에서 문자열 출력 형식을 설정하는 세 가지 방법에 대해 알아봅니다.

 

포맷 문자열(formatted string literals, f-string)

Python 3.6 이상에서 동작하는 문법이다.

문자열 앞에 f 혹은 F를 붙여 주고, 중괄호 {, } 안에 변수명을 써서 해당 변수를 참조하여 문자열을 만들 수 있다. 최신 파이썬에서 추가된 만큼 속도 또한 다른 문자열 형식에 비해 빠르다.

year = 2016
event = 'Referendum'
print(f'Results of the {year} {event}') # 'Results of the 2016 Referendum'

 

중괄호 안에서 연산을 수행할 수 있다.

box = 10
apple = 20
print(f'Total count: {box*apple}') # 200

 

str.format() 메서드

Python 3.0 이상에서 동작하는 방식이다.

문자열에 foramt 메서드(method)를 호출하여 변수명을 인자로 넘겨준다. 중괄호 안에 숫자를 지정해 넘겨받는 객체의 위치를 지정할 수 있다. f-문자열과 달리 foramt() 메서드는 중괄호 안에서 연산을 수행할 수 없다.

year = 2016
event = 'Referendum'
print('Results of the {0} {1}'.format(year, event)) # 'Results of the 2016 Referendum'

 

% 연산자

Python 2 이상에서 동작한다.

C언어의 printf 스타일의 문자열 포맷팅 방법과 같다. 오래된 방식이며 거의 사용하지 않는다.

year = 2016
event = 'Referendum'
print('Results of the %i %s' % (year, event)) # 'Results of the 2016 Referendum'

 

정수인 경우 %i, 문자열인 경우 %s 등 변수의 자료형에 맞는 형식 지정자를 써야 한다. 만약 잘못된 자료형을 쓰는 경우 에러가 난다. 위 코드에서 문자열을 %s가 아닌 %i로 지정할 경우 아래와 같이 에러가 발생한다.

year = 2016
event = 'Referendum'
print('Results of the %i %i' % (year, event)) # TypeError

 

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %i format: a number is required, not str

 

참고자료

 

7. Input and Output — Python 3.10.1 documentation

7. Input and Output There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities. 7.1. Fancier Output Formatting So far we

docs.python.org

 

PEP 498 -- Literal String Interpolation

The official home of the Python Programming Language

www.python.org

반응형

댓글