본문 바로가기

Study

[Python] format 함수와 이스케이프 문자

1. format()

- 중괄호 표시에 인자 값을 치환해 넣는 함수

1
2
3
4
5
6
7
8
9
10
11
12
#coding=utf-8
 
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)
 
# {} 안의 숫자는 생략 가능
print '{} was {} years old when he wrote this book'.format(name, age)
print 'Why is {} playing with that python?'.format(name)
 
cs

- 중괄호 안에 세부사항을 지정해 형식을 지정할 수 있다.
1
2
3
4
5
6
7
8
#coding=utf-8
 
# 소수점 이하 셋째 자리까지 부동 소숫점 숫자 표기 (0.333)
print '{0:.3f}'.format(1.0/3)
# 밑줄(_)로 11칸을 채우고 가운데 정렬(^)하기 (__hello__)
print '{0:_^11}'.format('hello')
# 사용자 지정 키워드를 이용해 (Swaroop wrote A Byte of Python) 표기
print '{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python')
cs


2. 이스케이프 문자
- \n, \t, \\ 와 같이 \를 붙인다.
- 이스케이프 문자를 그대로 표시하고 싶을 경우 print r"문자열" 혹은 print R"문자열" 형식을 사용하면 된다.
1
2
3
4
5
6
7
8
#coding=utf-8
 
# 이스케이프 문자 (\n)
print 'This is the first line\nThis is the second line.'
# 줄바꿈 방지
print "This is the first sentence. \ This is the second sentence."
# 순 문자열 표시 (이스케이프 문자 표시하기)
print r"Newlines are indicated by \n"
cs


3. print 함수는 출력후 줄바꿈을 포함하므로 줄을 바꾸고 싶지 않다면 print 함수 뒤에 쉼표(,)를 붙이면 된다.

1
2
3
4
5
#coding=utf-8
 
# 줄바꿈 없이 프린트 하기
print "a",
print "b"
cs