YUYANE

Python/ format() Method 본문

Programming Languages/PYTHON

Python/ format() Method

YUYA 2021. 1. 4. 16:58

The String format() Method

 

{}안에 들어가는 문자는 format 함수에 들어간 개체로 대체됨.

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

 

{} 안에 들어가는 숫자는 format 함수에 들어있는 개체의 순서를 나타내기도 한다.

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

 

{} 안에 매개 변수가 사용되면, format 함수에서 해당 매개 변수의 값을 참고한다.

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

 

positional arguments랑 keyword arguments랑 섞어서 사용할 수도 있다.

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

 

[]을 사용해서 해당 dict의 key 값에 접근할 수도 있다.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

 

 

참고

docs.python.org/3/tutorial/inputoutput.html

 

7. Input and Output — Python 3.9.1 documentation

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. 7.1. Fancier Output Formatting So far we

docs.python.org

 

Comments