Python 문자열 포맷

Chris·2019년 8월 29일
0

str.format(): Python 3.0+

str = 'Hello {}'.format('Chris')
# Hello Chris

test = 'Hello, {1}. count: {0}'
test.format(46, 'Chris')
# Hello, Chris. count: 46

f-string: Python 3.6+

a = 2
b = 3
test = f'sum: {a + b} | multiply: {a * b}'
# sum: 5, multiply: 6

% operator (old style)

d = '%s %d' % ('Chris', 2)
# Chris 2

Python 3.0이상부터는 old style을 가독성과 권장하지 않음.
속도는 f-string이 가장 빠름

Value conversion

class Data(object):

    def __str__(self):
        return 'str'

    def __repr__(self):
        return 'repr'

'{0!s} {0!r}'.format(Data())

# str repr

Padding and aligning strings

'{:>10}'.format('test')
# [][][][][][]test

'{:10}'.format('test')
# test[][][][][][]

'{:^6}'.format('zip')
# []zip[][]

Truncating long strings

{:.5}'.format('xylophone
# xylop

Named placeholders

'{first} {last}'.format(**data)
# Hodor Hodor!

Datetime

from datetime import datetime

'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
# 2001-02-03 04:05

dt = datetime(2001, 2, 3, 4, 5)
# 2001-02-03 04:05

Custom objects in datetime

from datetime import datetime

class HAL9000(object):

    def __format__(self, format):
        if (format == 'open-the-pod-bay-doors'):
            return "I'm afraid I can't do that."
        return 'HAL 9000'

'{:open-the-pod-bay-doors}'.format(HAL9000())

# I'm afraid I can't do that.

Output format

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
	print(f'{name:10} ==> {phone:10d}')

# Sjoerd     ==>       4127
# Jack       ==>       4098
# Dcab       ==>       7678
for x in range(1, 11)
	print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
  
#  1   1    1
#  2   4    8
#  3   9   27
#  4  16   64
#  5  25  125
#  6  36  216
#  7  49  343
#  8  64  512
#  9  81  729
# 10 100 1000

문서 참고 링크

https://docs.python.org/2/library/stdtypes.html#string-formatting
https://brownbears.tistory.com/421
https://pyformat.info/#number
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
https://docs.python.org/ko/3/tutorial/inputoutput.html

profile
올드보이 코더

0개의 댓글