Notice
Recent Posts
Recent Comments
07-04 23:18
Archives
관리 메뉴

develop myself

Python formatting: format() method, f-string 본문

DataScience/Python

Python formatting: format() method, f-string

insightous 2023. 1. 25. 14:33

.format() method

기본적인 방법

In [1]:

'We are the {} who say "{}!"'.format('knights', 'Ni')

Out[1]:

'We are the knights who say "Ni!"'

순서 명시

In [2]:

'{0} and {1}'.format('spam', 'eggs')

Out[2]:

'spam and eggs'

In [3]:

'{1} and {0}'.format('spam', 'eggs')

Out[3]:

'eggs and spam'

변수명 명시

In [4]:

'This {food} is {adjective}.'.format(
      food='spam', adjective='absolutely horrible')

Out[4]:

'This spam is absolutely horrible.'

In [5]:

'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
                                                   other='Georg')

Out[5]:

'The story of Bill, Manfred, and Georg.'

dict 타입을 사용하는 특이한 방법

In [6]:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

'Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table)

Out[6]:

'Jack: 4098; Sjoerd: 4127; Dcab: 8637678'

dict 타입을 사용하는 기본적 방법

In [7]:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)

Out[7]:

'Jack: 4098; Sjoerd: 4127; Dcab: 8637678'

자릿수 명시

In [8]:

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

In [9]:

yes_votes = 42_572_654
no_votes = 43_132_495
percentage = yes_votes / (yes_votes + no_votes)
'{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)

Out[9]:

' 42572654 YES votes  49.67%'

 

공식문서: format() 튜토리얼

https://docs.python.org/3/tutorial/inputoutput.html#the-string-format-method

 

7. Input and Output

There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities. Fa...

docs.python.org

 

f-string

f로 시작하는 문자열의 {}에 변수를 사용하는 방법. 예시 참고

이 방법을 주로 사용하고, f-string 방법 사용하기 까다로울 경우, 위의 format 메서드를 사용하는 것을 권장.

기본 방법

In [6]:

value = 4 * 20
f'The value is {value}.'

Out[6]:

'The value is 80.'

 

자릿수 명시

In [10]:

import math
f'The value of pi is approximately {math.pi:.3f}.'

Out[10]:

'The value of pi is approximately 3.142.'

위의 코드에서 math.pi가 변수, .3f는 포매팅 방법. 즉, float 타입의 소숫점 3자리까지.

 

 

In [11]:

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

Out[11]:

Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678
  • 문자열은 왼쪽 정렬.
  • d: decimal, 정수.
  • d를 사용함으로써 숫자로 타입 명시하고, 오른쪽 정렬

 

repr(representation) 차이 비교

In [12]:

animals = 'eels'
print(f'My hovercraft is full of {animals}.')

print(f'My hovercraft is full of {animals!r}.')

Out[12]:

My hovercraft is full of eels.
My hovercraft is full of 'eels'.

 

=를 사용하여 간편하게 표현

In [21]:

foo = "bar"
f"{ foo = }" # preserves whitespace

Out[21]:

" foo = 'bar'"

 

In [22]:

line = "The mill's closed"
f"{line = }"

Out[22]:

'line = "The mill\'s closed"'

 

In [23]:

f"{line = :20}"

Out[23]:

"line = The mill's closed   "

 

In [24]:

f"{line = !r:20}"

Out[24]:

'line = "The mill\'s closed" '

 

In [13]:

bugs = 'roaches'
count = 13
area = 'living room'
print(f'Debugging {bugs=} {count=} {area=}')

Out[13]:

Debugging bugs='roaches' count=13 area='living room'

 

conversion: !r, !s, !a

  • !r = repr()
  • !s = str()
  • !a = ascii()

In [14]:

name = "Fred"
f"He said his name is {name!r}."

Out[14]:

"He said his name is 'Fred'."

 

In [15]:

f"He said his name is {repr(name)}."  # repr() is equivalent to !r

Out[15]:

"He said his name is 'Fred'."

 

nested 방법

In [7]:

import decimal

width = 10
precision = 4
value = decimal.Decimal("12.34567")
f"result: {value:{width}.{precision}}"  # nested fields

Out[7]:

'result:      12.35'

date format 사용

In [18]:

from datetime import datetime

today = datetime(year=2017, month=1, day=27)
f"{today:%B %d, %Y}"  # using date format specifier

Out[18]:

'January 27, 2017'

 

In [19]:

f"{today=:%B %d, %Y}" # using date format specifier and debugging

Out[19]:

'today=January 27, 2017'

 

16진수

In [20]:

number = 1024
f"{number:#0x}"  # using integer format specifier

Out[20]:

'0x400'

 

공식문서

 


번외: f-string보다 format() 메서드를 사용하기 편리한 경우

lambda 함수를 사용할 경우

df = pd.DataFrame(b, columns=['Lemon'])
df['Lemon'].map(lambda x: '{:.2f}'.format(x))

 

'DataScience > Python' 카테고리의 다른 글

matplotlib basic tips  (0) 2023.01.26
pandas basic tips  (0) 2023.01.26
numpy basic tips  (0) 2023.01.26
Python help, dir  (0) 2023.01.26
jupyter notebook magic commands, shell commands  (0) 2023.01.26
Comments