때때로 다른 정보들을 이용하여 문자열을 만들 필요가 있다.
이 때, 유용한 메소드가 format()이다.
다음과 같은 코드를 보자.
age = 20 name = 'Swaroop'
print('{0} was {1} years old when he wrote this book'.format(name, age)) print('Why is {0} playing with that python?'.format(name)) |
위 프로그램을 실행시키면,
Swaroop was 20 years old when he wrote this book
Why is Swaroop playing with that python?
과같은 결과가 출력된다.
문자는 특정한 명세 사항(specification)을 통해 사용될 수 있다.
format 메소드는 명세 사항을 상응하는 인자(argument)들로 치환하기 위하여 호출될 수 있다.
첫번째 사용에서 우리는 {0}을 사용하여 format 메소드의 첫번째 인자인 name와 맞춘다(상응하게 한다).
비슷하게, 두번째 명세 사항은 인자 age와 상응하는 {1}이다.
기억해라, 파이썬은 숫자를 셀 때 0부터 시작한다는 것을, 당연히 두번째는 1이고, 이런식으로 증가하게 된다.
이 format() 메소드 대신에
print('Why is ' + name + ' playing with that python?')
과 같이 쓸 수 있으며,
또한, 중괄호 안의 숫자는 선택 사항이다.
print('{} was {} years old when he wrote this book'.format(name, age))
print('Why is {} playing with that python?'.format(name))
과 같이 써도 같은 결과가 출력될 것이다.
print('{0:.3f}'.format(1.0/3)) print('{0:_^11}'.format('hello')) print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python')) |
위의 코드를 보면 첫번째 줄은 소수점 3자리까지 출력하라는 것이고,
두번째 줄은 치환될 문자를 가운데에 위치시켜 (_)밑줄로 채우라는 것이며,
마지막 줄은 숫자가 아닌 키워드 기반으로 치환시키라는 것이다.
0.333
___hello___
Swaroop wrote A Byte of Python
위와 같은 결과를 출력할 것이다.
지금 format하는 것에 관하여 다루고 있으므로, print 메소드는 항상 보이지 않는 새로운 줄(\n)을 가지고 있다는 것을 알아두자.
이것은 print() 메소드가 호출될 때 마다 분리된 줄에 출력하기 위함이다.
이것을 원하지 않는다면, print() 메소드뒤에 end를 함께 쓰자.
print('a', end='') print('b', end='') |
위의 코드는
ab
의 결과를 출력할 것이다.
print('a', end=' ') print('b', end=' ') print('c', end=' ') |
위의 코드는
a b c
의 결과를 출력할 것이다.