문자열 포매팅(Formatting)

✒️ 2025-05-19 10:32 내용 수정

Do it! 점프 투 파이썬(2017년 발행) 내용을 정리


문자열 안에 어떤 값을 삽입하는 방법

코드 타입
%s 문자열(String)
%c 문자(char)
%d 정수(Integer)
%f 실수/부동소수(Float)
%o 8진수(Oct)
%x 16진수(Hex)
`" % 95
'Progress : 95%'

- **2개 이상의 값을 바로 대입할 때는 `(,)`로 구분**하여 넣는다.
```python
>>> "%d %s apples" % (5, "red")
'5 red apples'
>>> number = 10
>>> "%d minutes left." % number
'10 minutes left.'
""" 
5개 길이 중 3글자를 제외하고 
왼쪽에 공백 2개가 추가
"""
>>> "This is the %5s" % "end"
'This is the   end'

""" 
5개 길이 중 3글자를 제외하고 
오른쪽에 공백 4개가 추가
"""
>>> "This is the %-7s." % "end"
'This is the end    .'

"""
삽입할 문자열 길이가 숫자보다 크면
공백 없이 문자열 전체를 넣는다
"""
>>> "This is the %5s" % "end of the road"
'This is the end of the road'
>>> "%0.3f" % 3.141592
'3.142'

>>> "%10.5f" % 3.1415926535897932
'   3.14159'

2. 포맷 함수 사용

>>> "It costs %d dollars".format(100)
'It costs %d dollars'
>>> "It costs {0} dollars".format(100)
'It costs 100 dollars'

>>> "Five {0} apples".format("golden")
'Five golden apples'

>>> "Progress : {0}%".format(95)
'Progress : 95%'
>>> "{{ and }}".format()
'{ and }'
>>> number = 5
>>> "{0} red apples".format(number)
'5 red apples'
>>> number = 5
>>> "{0} {1} apples".format(number,"red")
'5 red apples'

>>> "{1} {0} apples".format(number,"red")
'red 5 apples'
>>> "Today is {month}/{date}/{year}".format(year=2025, month=3, date=28)
'Today is 3/28/2025'
# 인덱스 항목으로 넣을 값을 마지막에 배치한 경우
>>> "Today is {month}/{date}/{2}".format(date=10, month=2, 2025)
  File "<python-input-67>", line 1
    "Today is {month}/{date}/{2}".format(date=10, month=2, 2025)
                                                               ^
SyntaxError: positional argument follows keyword argument

# 인덱스 항목으로 넣을 값을 맨 처음에 배치
>>> "Today is {month}/{date}/{0}".format(2025, date=10, month=2)
'Today is 2/10/2025'
>>> "{0:<10}".format("hello")
'hello     '

>>> "{0:>10}".format("test")
'      test'

>>> "{0:^10}".format("aaaa")
'   aaaa   '

>>> "{0:*^10}".format("aaaa")
'***aaaa***'
>>> pi = 3.1415926535897932
>>> "{0:0.3f}".format(pi)
'3.142'

>>> "{pi:10.2f}".format(pi=3.14)
'      3.14'

3. f 문자열 포매팅

>>> number = 10
>>> color = "blue"
>>> f'{number} {color} berries'
'10 blue berries'
>>> hour = 12
>>> f"{hour + 3} hours left."
'15 hours left.'
>>> f'{"aa":<8}'
'aa      '

>>> f'{"aa":>8}'
'      aa'

>>> f'{"aa":^8}'
'   aa   '

>>> f'{"aa":*^8}'
'***aa***'
>>> pi = 3.141592

>>> f'{pi:5.3f}'
'3.142'

>>> f'{pi:10.3f}'
'     3.142'
>>> f"{10298493883:,}"
'10,298,493,883'