티스토리 뷰

python

문자열 포맷팅

hs_seo 2014. 12. 24. 11:29

[string 포맷팅]

 

python 의 문자열 포맷팅은 두가지 방법을 사용한다.

  - .format()

  - %

두가지 방법중 어떤 방법을 사용해도 상관없다.

% 를 이용하는 것이 권장되고 있는 것 같다.

 

 <소스코드>

#!/usr/bin/python
# -*- coding : utf-8 -*-

 

# format 이용
sentence1 = 'I am a {}'
print sentence1.format("boy")

 

# format 에 리스트와 dict 를 이용한 방법
sentence3 = "I am a {0} and {x}"
print sentence3.format("boy", x="girl")

 

# % 와 dict 를 이용한 방법
sentence2 = "I am a boy %(x)s"
print sentence2 % { "x" : "too"}

 

# % 와 튜플을 이용한 방법
sentence4 = "I am a %s"
print sentence4 % ( "boy", ) 

 

 

<참고>

http://www.diveintopython.net/native_data_types/formatting_strings.html

https://infohost.nmt.edu/tcc/help/pubs/python/web/new-str-format.html

http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format

https://docs.python.org/2/library/stdtypes.html#str.format


반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함