파이썬 문자열 포맷팅

(파이썬 문자열 포메팅에서 넘어옴)

1 개요[ | ]

Python String Formatting, Python String Interpolation
파이썬 문자열 포맷팅, 파이썬 문자열 인터폴레이션
apples = 4
print("I have {0} apples".format(apples))
print("I have {a} apples".format(a=apples))
print("I have {} apples".format(apples))
print(f"I have {apples} apples")

2 format 메소드[ | ]

인덱스 사용
print( "{0} + {1} = {2}".format(1, 2, 3) ) # 1 + 2 = 3
→ 인덱스 0에 1, 인덱스 1에 2, 인덱스 2에 3이 각각 매칭된다.
이름 사용
print( "{name} is best.".format(name="zetawiki") ) # zetawiki is best.
→ name 에 "zetawiki"가 대입되었다.

3 f문자열[ | ]

apples = 4
print(f"I have {apples} apples")

4 % 연산자 (구식)[ | ]

  • % 연산자 사용은 권장되지 않는다.
숫자
print( "%d + %d = %d" % (1, 2, 3) ) # 1 + 2 = 3
문자
print( "zetawik%c" % "i" ) # zetawiki
문자열
print( "zeta and %s" % "wiki" ) # zeta and wiki
변수 사용
x = 3
print( "x is %d" % x ) # x is 3

5 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}