파이썬 문자열 포맷팅(formating) 방법

yurimLee·2023년 1월 11일
0

1. Operater %

  • %d 정수
  • %s 문자열
  • %f 실수
print("My name is %s, I'm %d and %fcm" % ('John', 36, 180))
txt = "My name is %s, I'm %d and %.0fcm"
print(txt % ('John', 36, 180))
My name is John, I'm 36 and 180.000000cm
My name is John, I'm 36 and 180cm

2. str.format()

formating Types
https://www.w3schools.com/python/ref_string_format.asp

1. 인덱스 생략

  • 순차적 실행
txt = "My name is {}, I'm {}".format("John",36)
print(txt)
My name is John, I'm 36
txt = "The price is {:.2f} dollars."
print(txt.format(45))
The price is 45.00 dollars.

2. 인덱스 부여

  • 인덱스 시작 값 0부터 실행
txt = "My name is {0}, I'm {1}".format("John",36)
print(txt)
My name is John, I'm 36

3. 변수 지정 + 값 대입

txt = "My name is {name}, I'm {age}".format(name = "John", age = 36)
print(txt)
My name is John, I'm 36
txt = "For only {price:.2f} dollars!"
print(txt.format(price = 49))
For only 49.00 dollars!

3. f-String

name = "John"
age = 36
height = 180
print(f'My name is {name}, I\'m {age} and {height}cm')

0개의 댓글