1️⃣패턴 1
format 함수의 인수를 차례로 {} 에 대입
2️⃣패턴 2
{} 안에 변수가 있다면, format의 인수에 그 변수를 대입할 수 있음
3️⃣패턴 3
일반 변수 대신 : 를 붙여 포매팅 표현식임을 명시하고, .2f 를 붙여 반올림 후 2째자리 까지 표시
4️⃣패턴 4
:>3 처럼 3자리 들여쓰기로 0~3자리 문자열 와도 들여쓰기 보장
name = "Manny"
number = len(name) * 3
# 패턴 1
print("Hello {}, your lucky number is {}".format(name, number)) # Hello Manny, your lucky number is 15
# 패턴 2
print("your lucky number is {number}, {name}.".format(name=name, number=number)) # your lucky number is 15, Manny.
def student_grade(name, grade):
return "{X} received {Y}% on the exam".format(X=name, Y=grade)
print(student_grade("Reed", 80))
print(student_grade("Paige", 92))
print(student_grade("Jesse", 85))
# Reed received 80% on the exam
# Paige received 92% on the exam
# Jesse received 85% on the exam
# 패턴3 - 반올림
price = 7.5
with_tax = price * 1.09
print(price, with_tax) # 7.5 8.175
# : 는 일반 문자열과 구분을 위해 사용
# .2f 는 소수점 2째 자리까지 반올림을 의미
print("Base price: ${:.2f}. With Tax: ${:.2f}".format(price, with_tax)) # Base price: $7.50. With Tax: $8.18
# 문자열 포매팅에서 자바스크립트처럼 $를 활용하지 않고 단순히 {}를 사용
# 화씨를 섭씨로 변환
def to_celsius(x):
return (x - 32) * 5 / 9
for x in range(0, 101, 10):
# >3 은 3자리 들여쓰기를 의미 (0 ~ 3자리 들어와도 ㅇㅋ)
print("{:>3} F | {:>6.2f} C".format(x, to_celsius(x)))
# 0 F | -17.78 C
# 10 F | -12.22 C
# 20 F | -6.67 C
# 30 F | -1.11 C
# 40 F | 4.44 C
# 50 F | 10.00 C
# 60 F | 15.56 C
# 70 F | 21.11 C
# 80 F | 26.67 C
# 90 F | 32.22 C
# 100 F | 37.78 C
📍추가
1️⃣{} 안에 숫자를 넣으면 매개변수 번호를 바인딩 가능
# "{0} {1}".format(first, second)
first = "apple"
second = "banana"
third = "carrot"
formatted_string = "{0} {2} {1}".format(first, second, third)
print(formatted_string)
"""Outputs:
apple carrot banana
"""
2️⃣포매팅 표현식
3️⃣포매팅된 문자열 리터럴
문자열 앞에 f를 넣고, 전역 변수 활용 가능
name = "Magic"
print(f"{name} Johnson") # Magic Johnson
item = "Purple Cup"
amount = 5
price = amount * 3.025
print(f"-item: {item} -Amount: {amount} -Price: {price:.2f}")
# -item: Purple Cup -Amount: 5 -Price: 15.12