https://docs.python.org/3/tutorial/inputoutput.html#manual-string-formatting

수동 포맷팅
문자열을 기준으로 길이를 계산

  • rjust/ljust/center(width):
    • 문자열을 지정 폭에 맞춰 오른쪽/왼쪽/가운데 정렬하고 공백으로 패딩한 새 문자열 반환(원본 변경 없음). 길이가 더 길면 그대로 반환.
  • zfill(width):
    • 숫자 문자열 왼쪽을 0으로 채움. 부호(+/-)는 앞에 두고 나머지에 0을 채움.
'12'.zfill(5)
# '00012'
 
'-3.14'.zfill(7)
# '-003.14'
 
'3.14159265359'.zfill(5)
# '3.14159265359'
  • 잘라내기 필요 시:
    • x.ljust(n)[:n]처럼 슬라이싱으로 최대 길이 제한.
  • f-string/format 없이 직접 정렬·패딩을 제어할 때 유용하지만, 복잡한 포맷은 f”…{expr:spec}…”나 str.format이 더 간결하다.

옛날 format
문법: “format % values” 형태로 % 자리에 값을 치환.

import math
 
print('The value of pi is approximately %5.3f.' % math.pi)
# he value of pi is approximately 3.142.

← python 3.14으로