[프로그래밍언어][공통] 서식 지정자 / 형식 문자(열) ( String Formatting )

728x90

 

<  서식 지정자 / 형식 문자(열)  ( String Formatting )  >

 

 

◆  기존 문자열 포맷팅  ( Old String Formatting )

 

■  형식

  %    [ flags ]  [ width ]  [ . precision ]    specifier_character  

 

■  서식 지정자 / 형식 문자  ( Specifier Character )

서식 지정자 출력형태 ( Output ) Java C
c , C 단일 문자 (유니코드)  ( 대소문자 구분 ) char, int, short char, int, short
s , S 문자열  ( 대소문자 구분 ) String, char, int, short, long, double, float char[], char*
d 10진 정수 int, short, long int, short, long, char
10진 정수 - int, short, long, char
u 10진 정수  ( 부호 없음 ) - int, short, long, char
o 8진 정수  ( 부호 없음 ) int, short, long int, short, long, char
x , X 16진 정수  ( 대소문자 구분 ) int, short, long int, short, long, char
f , F 부동 소수점 숫자   ( 대소문자 구분 ) double, float double, float
e , E 부동 소수점 숫자  ( e or E 표기법 ) double, float double, float
g , G 부동 소수점 숫자  ( 값에 따라 %f 또는 %e 선택 ) double, float double, float
a , A 16진수 부동 소수점 숫자  ( 대소문자 구분 ) double, float double, float
t , T 날짜 또는 시간  ( 뒤에 날짜·시간 표시 형식 문자 추가 ) Date -
% % 기호 출력  ( 리터럴 ) ( literal ) ( literal )
n 줄바꿈 출력 String -
p 주소 출력 - void*
날짜/시간
형식지정자
설명
H 24-hour format of an hour 00 to 23
I 12-hour format of an hour 01 to 12
k 24-hour format of an hour 0 to 23
l 12-hour format of an hour 1 to 12
M Minutes with leading zeros 00 to 59
S Seconds with leading zeros 00 to 59
L Milliseconds with leading zeroes 000 to 999
N Nanoseconds with leading zeroes 000000000 to 999999999
p "am", "pm", "AM" or "PM" to indicate morning or afternoon  
B A full textual representation of a month January through December
A A full textual representation of a day ex)  Monday
a A short textual representation of a day ex)  Mon
C The first two digits of the year ex)  2025 -> 20
Y A four digit representation of a year ex)  2025
y A two digit representation of a year ex)  25
j The day of the year with leading zeroes 001 to 366
m A numeric representation of a month 01 to 12
d The day of the month 01 to 31
e The day of the month without leading zeros 1 to 31
R The time in 24-hour format ex)  21:30
T The time in 24-hour format with seconds ex)  21:30:02
r The time in 12-hour format with seconds ex)  09:30:02 PM
D Date representation as month/day/year ex)  12/17/23
F Date representation as year-month-day ex)  2023-12-17
c Full date and time ex)  Thu Mar 28 10:51:00 EDT 2024

 

더보기
서식 문자 출력 형태 Java C
%c  단일 문자 char, int, short char, int, short
%s  문자열 String, char, int, short, long, double, float char[], char*
%d 부호 있는 10진 정수 int, short, long int, short, long, char
%i  부호 있는 10진 정수 - int, short, long, char
%u 부호 없는 10진 정수 - int, short, long, char
%o 부호 없는 8진 정수 int, short, long int, short, long, char
%x, %X 부호 없는 16진 정수 ( 대소문자 구분 ) int, short, long int, short, long, char
%f 부호 있는 10진 실수 ( 소수점 6자리 이하 ) double, float double, float
%e, %E e or E 표기법에 의한 실수 double, float double, float
%g, %G 값에 따라서 %f 또는 %e 선택 double, float double, float
%% % 기호 출력 ( 리터럴 ) ( literal ) ( literal )
%p 주소 출력 - void*

 

 

 

■  플래그  ( Flags )

플래그  ( Flags ) 설명  ( Description ) 예  ( Example )
0 공백이 0으로 채워짐 %015d ☞   "000000012345678"
없음  ( none ) 오른쪽 정렬  ( 기본 ) %15d ☞   " _______12345678"
- 왼쪽 정렬 %-15d ☞   "12345678_______"
+ 선행 '+' 기호 포함 %+15d ☞   "______+12345678"
공백  ( space ) 선행 공백 포함 ( 양수 값 ) %- 15d ☞   "_12345678______"
, 1000 단위 구분 기호 포함 %,15d ☞   "_____12,345,678"
# 소수점 강제 표출
( a/A, e/E, f/F, g/G 와 함께 사용 시 )
%#.3f ☞   "5.000"

 

■  폭  ( Width )

폭  ( Width ) 설명  ( Description )
숫자  ( number ) 인쇄할 최소 문자 수.
인쇄할 값이 이 숫자보다 짧으면 결과에 공백이 채워짐. 결과가 더 크더라도 값은 잘리지 않음.
* 형식 문자열에 지정되지 않고, 형식 지정 인수 앞에 추가 정수 값 인수로 지정됨.

 

■  정밀도  ( Precision )

정밀도  ( Precision ) 설명  ( Description )
숫자  ( number ) -  정수 지정자 ( d , i , o , u , x,X )  :  최소 숫자 자리수. 짧으면 뒤에 0이 채워짐. 결과가 더 길더라도 값은 잘리지 않음.
-  부동 소수점 숫자 지정자 ( a,A, e,E, f,F )  :  소수점 뒤에 인쇄할 숫자 자리수  ( 기본값 : 6 )
-  g,G 지정자  :  인쇄할 유효 숫자 최대 수
-  s 지정자  :  인쇄할 문자 최대 수  ( 기본값 : 0 )
* 형식 문자열에 지정되지 않고, 형식 지정 인수 앞에 추가 정수 값 인수로 지정됨.

  ( 예) "%.3f"  ☞  소수점 세 번째 자리까지 표현 )

 

□  출처  :

https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
https://cplusplus.com/reference/cstdio/printf/
https://www.w3schools.com/java/ref_string_format.asp

 

□  자바(Java) 예제   :

double d; int n;  int m;

// ex) 소수점 m 번째 자리까지 표현
String format1 = String.format("%.3f", d);          // ex) 소수점 3 번째 자리
String format2 = String.format("%." + m + "f", d);  // ex) 소수점 m 번째 자리

// ex) m 자리로 맞춰 표현 (빈 공간은 0 으로 채움)
String format3 = String.format("%02d", n);          // ex) 두 자리 (한 자리 수일 경우 앞에 0)
String format4 = String.format("%0" + m + "d", n);  // ex) m 자리

( Java String Class  ☞  https://hyunjiishailey.tistory.com/473 )

 


 

◆  향상된 문자열 포맷팅  ( Advanced String Formatting )

 

■  형식

  {  :    [  [ fill ]  align ]  [ sign ]  [ # ]  [ 0 ]  [ minimum_width ]  [ . precision ]  [ type ]    }  

 

■   채우기  ( fill )

    < any character >

■   정렬  ( align )

  :  최소 너비가 정의되어있을 경우에만 유효

정렬 플래그  ( Align flag ) 설명  ( Description )
< 왼쪽 정렬  ( 기본 )
> 오른쪽 정렬
= 기호 : 왼쪽 정렬,  숫자 : 오른쪽 정렬  ( 숫자 유형에만 유효 )
^ 중앙 정렬

 

■   부호  ( sign )

  :  숫자 유형에만 유효

부호 플래그  ( Sign flag ) 설명  ( Description )
+ 모두 부호 표시
- 음수만 부호 표시  ( 기본 )
공백  ( space ) 양수 앞에 공백

 

■   #

  :  정수의 경우 대체 형식 사용  ( 2진수, 8진수, 16진수는 각각 '0b', '0o', '0x' )

■   0

  :  '0' 패딩  ( '=' 로 중앙정렬하여  '0' 문자로 채우는 것과 같음 )

 

■   폭  ( width )

  :  최소 필드 너비 정의  ( 기본값 : 값의 크기 )

 

■   정밀도  ( precision )

  -  부동 소수점  :  소수점 뒤 표시할 자릿수
  -  문자  :  최대 필드 크기
  -  정수  :  무시됨

 

■   유형  ( type )

서식 지정자 출력형태  ( Output )
b 이진수
c 문자  ( 정수의 경우 유니코드 문자 )
d 10진수 정수  ( 기본 )
o 8진수 정수
x , X 16진수 정수  ( 9보다 큰 숫자 대소문자 구분 )
n 숫자  ( 현재 로캘 사용하여 적절한 문자 삽입 )
-  정수  :  d 와 동일
-  부동 소수점  :  g 와 동일
e , E 지수 표기  ( 대소문자 구분 )
f , F 고정 소수점  ( 대소문자 구분 )
g , G 고정 소수점  ( 값에 따라 f 또는 e 로 변환 )  ( 기본값 ( 소수점 뒤 최소 한 자리 인쇄 ) )
% 백분율  ( 숫자를 100으로 곱하고 고정( f ) 형식으로 표시한 다음 % 기호 붙임 )

 

□   출처   :

https://docs.python.org/3/library/string.html#format-specification-mini-language
https://peps.python.org/pep-3101/#standard-format-specifiers

 

□   파이썬(Python) 예제   :

# ex) 소수점 m 번째 자리까지 표현
format1 = "{:.3f}".format(d)                 # ex) 소수점 3 번째 자리
        = "%.3f" % d
        = f"{d:>.3f}"
format2 = ("{:>." + str(m) + "f}").format(d)  # ex) 소수점 m 번째 자리
        = ("%." + str(m) + "f") % d
        
# ex) 소수점 m 번째 자리에서 반올림하여 표현  ( f 없음 )
format5 = "{:.3}".format(d)                   # ex) 소수점 2 번째 자리까지
        = f"{d:>.3}"
format6 = ("{:>." + str(m) + "}").format(d)   # ex) 소수점 m-1 번째 자리까지
        = ("%." + str(m)) % d

# ex) m 자리로 맞춰 표현 (빈 공간은 0 으로 채움)
format3 = "{:>02d}".format(n)             # ex) 두 자리 (한 자리 수일 경우 앞에 0) (d 생략 가능)
        = "%02d" % n
        = f"{n:>02d}"
format4 = ("{:>0" + m + "2d}").format(n)  # ex) m 자리
        = ("%0" + str(m) + "d") % n

( Python Common String and Operations  ☞  https://docs.python.org/3/library/string.html#string.Formatter )

 

 

반응형