SSAMKO의 개발 이야기

파이썬 문자열 포매팅 (string formatting) | python3 본문

Python

파이썬 문자열 포매팅 (string formatting) | python3

SSAMKO 2020. 3. 31. 00:32
반응형

python에는 크게 세 가지 string 포맷이 존재한다.

 

1. 가장 오래된 방식인 %-포맷

name = 'ssamko'
age = 20

print('He is %s. %d years old' % (name, age))

 위와 같이 %s(string), %d(int) 등을 이용하여 string내에 표현해주고 뒤에 각각에 해당하는 변수를 넣어주는 방법이다. 변수의 타입에 따라 %s, %d처럼 달리 지정해줘야하기 때문에 변수의 타입을 지정하지 않고 선언하는 파이썬의 특징과 상충하는 면이 있다.

 

2. 그 후로 추가된 str.format() 메서드 방식

name = 'ssamko'
age = 20

print('He is {}. {} years old'.format(name, age))
print('He is {0}. {1} years old'.format(name, age))

 좀 더 파이썬 답게 변수의 타입을 지정해주지 않고도 사용이 가능해졌다. 

타입의 중요성이 대두되고 있지만, 역시나 파이썬의 장점은 개발이 빠르다는 데에 있으니까요.

 string 안에 중괄호로 변수가 들어갈 자리를 표시해주고, .format()메서드의 인자로 변수를 넣어주는 방식이다. 빈 중괄호는 인자를 차례대로 넣고, {0}, {1} 처럼 index를 넣어줄 수도 있다.

print('He is {1}. {0} years old'.format(age, name))

당연히 인자의 순서와 상관없이 index로 자리를 찾아주는 것도 가능하다.

print('He is {name}. {age} years old and from {hometown}.'.format(hometown='CJ', age=20, name='ssamko'))

이렇게 변수명을 직접 입력해 줄 수도 있고,

profile = {
    'name': 'ssamko',
    'age': 20,
    'hometown': 'CJ'
}

print('He is {name}. {age} years old and from {hometown}.'.format(**profile))

인자에 dictionary를 unpacking해서 넣는 것도 가능하다.

 

3. f-string

name = 'ssamko'
age = 20
hometown = 'CJ'

print(f'He is {name}. {age} years old and from {hometown}')

 위에서 처럼 string 표현앞에 f를 붙여준다. 그리고 str.format() 처럼 중괄호 안에 변수명을 넣어주면 끝난다. 세 가지 방법 중 가장 최근에 나온 방법이고, 가장 표현이 간단하다. dictionary를 구성하지 않고도 위 방법보다도 간단하게 표현할 수 있다.

 

3.1. 문자열 포매팅

 3.1.1. 공백 추가

fruit = 'strawberry'
price = 300

print(f'{fruit:10} ==> {price:5}')

정렬을 맞추기 위해 문자열에 공백을 추가하려면 변수명 뒤에 :(공백 수) 를 넣어주면 된다.

strawberry ==>   300

문자는 왼쪽 정렬, 숫자는 오른쪽 정렬이 default

fruits = ['strawberry', 'apple', 'banana']
prices = [300, 1300, 12500]

for i in range(3):
    print(f'{fruits[i]:10} ==> {prices[i]:5}')
for i in range(3):
    print(f'{fruits[i]:>10} ==> {prices[i]:5}')
for i in range(3):
    print(f'{fruits[i]:^10} ==> {prices[i]:5}')

f' '안에 당연히 리스트 안의 값도 넣을 수 있다.

> ^ 등 Format Specific Mini-Language를 이용해 정렬을 할 수도 있다.

# 출력
strawberry ==>   300
apple      ==>  1300
banana     ==> 12500
strawberry ==>   300
     apple ==>  1300
    banana ==> 12500
strawberry ==>   300
  apple    ==>  1300
  banana   ==> 12500

* Format Specific Mini-Language 공식문서

 

단, 아쉬운 점은 한글은 정렬이 제대로 되지 않는다는 점이다.

fruits = ['딸기', '사과', '바나나']
prices = [300, 1300, 12500]

for i in range(3):
    print(f'{fruits[i]:10} ==> {prices[i]:5}')
for i in range(3):
    print(f'{fruits[i]:>10} ==> {prices[i]:5}')
for i in range(3):
    print(f'{fruits[i]:^10} ==> {prices[i]:5}')
# 출력
딸기         ==>   300
사과         ==>  1300
바나나        ==> 12500
        딸기 ==>   300
        사과 ==>  1300
       바나나 ==> 12500
    딸기     ==>   300
    사과     ==>  1300
   바나나     ==> 12500

3.1.2. 0 Leading Integer

x = 2
print(f'{x:04d}')

3.1.3. 소수점 자리수 표현

a = 0.002345
print(f'{a:.3f}')

>> 0.002

3.2 날짜 포매팅

now = datetime.datetime.now()

print(f'today is {now:%A}. {now:%H %p}')

 위 처럼 date format은 콜론(:)뒤에 datetime format code를 사용해서 표현해주면 된다.

today is Tuesday. 03 AM

* datetime format code 공식문서

반응형
Comments