logo

파이썬에서 문자열 보간하는 방법 📂프로그래밍

파이썬에서 문자열 보간하는 방법

f-string

f-string은 파이썬 3.6부터 사용할 수 있으며 문자열 보간법 중 가장 간단하고 편리한 방법이다. 문자열 앞에 f를 뭍이고, 문자열 안에서 변수를 {변수}와 같이 사용하면 된다.

>>> name = 'An, Yujin'
>>> birthday = '2003'
>>>
>>> print(f'The leader of IVE is {name}, and she was born in {birthday}.')
The leader of IVE is An, Yujin, and she was born in 2003.

str.format()

문자열에 .formar() 매서드를 사용해서 보간할 수 있다. f-string 방법에 비해 가독성이 현저히 떨어진다. 변수의 자리를 빈 중괄호 {}로 비워놓고, 매서드에 순서대로 인자를 넣으면 된다.

>>> name = 'An, Yujin'
>>> birthday = '2003'
>>>
>>> print('The leader of IVE is {}, and she was born in {}.'.format(name, birthday))
The leader of IVE is An, Yujin, and she was born in 2003.
>>>
>>> print('The leader of IVE is {name}, and she was born in {birthday}.'.format(name='An, Yujin', birthday='2003'))
The leader of IVE is An, Yujin, and she was born in 2003.

C 스타일 보간법

%를 사용하여 다음과 같이 보간할 수 있다.

>>> print('The leader of IVE is %s, and she was born in %d.' % ('An, Yujin', 2003))
The leader of IVE is An, Yujin, and she was born in 2003.

Template

string 모듈의 Template 클래스를 활용하여 보간할 수 있다.

>>> from string import Template
>>>
>>> template = Template("The leader of IVE is $name, and she was born in $birthday.")
>>> str = template.substitute(name='An, Yujin', birthday=2003)
>>> print(str)
The leader of IVE is An, Yujin, and she was born in 2003.

환경

  • OS: Windows11
  • Version: Python 3.11.5