728x90
파이썬에서 유용한 string의 Template 라이브러리에 대해 소개하고자 합니다. 파이썬을 조금이라도 다뤄보신 분이라면 문자열 포매팅이 얼마나 자주 사용되는지 아실 텐데요, string.Template는 이러한 문자열 포매팅을 더 안전하고 명확하게 해주는 훌륭한 도구입니다. 그중에서 함수 subtitute에 대해 소개해드리려고 합니다.
선언 방법
from string import Template
template = Template(str) # Template에 추가할 문자열
대체할 문자열 표시하는 방법
첫번째 방법 : $ 와 공백을 사용하여 표시
from string import Template
text = "Hello, my name is $name and my hobby is $hobby"
# name 과 hobby를 대체할 변수로 만듦
# $ 와 공백을 이용하여 변수 생성
두번째 방법 : $ 와 { }를 사용하여 표시
두 번째 방법을 사용하는 이유는 변수 뒤에 공백 대신 문자가 올 때 변수명으로 선언되지 않기 위해 사용
from string import Template
text = "Hello, my name is ${name}, my hobby is ${hobby}"
# name 과 hobby를 대체할 변수로 만듦
# $ 와 괄호를 이용해 변수를 생성
Template.substitute
Template.substitute(dict or key)
딕셔너리 대신 매개변수를 각각 입력하는 경우
from string import Template
text = "Hello, my name is ${name}, my hobby is ${hobby}"
template = Template(text)
print(template.substitute(name="gil", hobby="coding"))
# Hello, my name is gil, my hobby is coding
string.Template는 $를 사용하여 변수를 표시합니다. 이는 문자열 내에서 동적인 부분을 명확하게 표시하고, 나중에 이 부분들을 다른 값으로 대체할 수 있게 해 줍니다.
딕셔너리로 입력하는 경우
from string import Template
text = "Hello, my name is ${name}, my hobby is ${hobby}"
template = Template(text)
tmp = dict(name="gil", hobby="coding") # {name="gil", hobby="coding"}
print(template.substitute(tmp))
# Hello, my name is gil, my hobby is coding
딕셔너리를 이용해 간단하게 매개변수를 전달할 수 있습니다.
매개변수가 누락된 경우
from string import Template
text = "Hello, my name is ${name}, my hobby is ${hobby}"
template = Template(text)
# hobby 매개변수를 입력하지 않은 경우
print(template.substitute(name="gil"))
# KeyError: 'hobby'
hobby라는 Key가 없어서 KeyError를 발생시킨다.
'Coding > Python' 카테고리의 다른 글
[Python] Jupyter Notebook 가상환경 커널 추가 및 삭제 (0) | 2024.01.11 |
---|---|
[Python] *args 와 **kwargs의 차이 (0) | 2024.01.03 |
[Python] 가상환경 생성과 삭제, 활성화 및 비활성화(MacOS, Windows) (1) | 2023.12.27 |
[Python] for else구문과 while else구문 정리 (0) | 2023.11.30 |
[Python] round의 사사오입과 오사오입에 대해 (0) | 2023.11.26 |