Python f-string 문자열 포매팅
f-strings는 변수와 식을 텍스트 안에 바로 넣을 수 있게 해 줍니다. 콜론 뒤의 format specifier는 소수점, 너비, 정렬, 구분 기호를 조절합니다.
f-string 문자열 포매팅이란?
f-strings는 변수와 식을 텍스트 안에 바로 넣을 수 있게 해 줍니다. 콜론 뒤의 format specifier는 소수점, 너비, 정렬, 구분 기호를 조절합니다.
Python f-strings와 format specifier로 읽기 쉬운 출력을 만듭니다.
언제 사용하나요?
- 실행 가능한 코드로 Python 문법을 학습합니다.
- 더 큰 문제를 위한 기초를 다집니다.
- 로컬 설치 없이 아이디어를 빠르게 시험합니다.
예제 코드
main.py
name = "Lin"
score = 92.456
items = 3
# f-strings put expressions inside {} directly in the text.
print(f"{name} scored {score} points")
# Format specifiers after a colon control how values look.
print(f"Rounded: {score:.1f}")
print(f"Price: ${19.5:.2f}")
print(f"Padded: [{items:>5}] [{items:<5}] [{items:^5}]")
print(f"Thousands: {1234567:,}")
print(f"Percent: {0.875:.0%}")
# Any expression works, including calls and arithmetic.
print(f"{name.upper()} has {items * 2} tickets")
# A table with aligned columns.
for product, price in [("Tea", 2.5), ("Coffee", 3.75)]:
print(f"{product:<8}{price:>6.2f}")
예상 출력
Lin scored 92.456 points
Rounded: 92.5
Price: $19.50
Padded: [ 3] [3 ] [ 3 ]
Thousands: 1,234,567
Percent: 88%
LIN has 6 tickets
Tea 2.50
Coffee 3.75
작동 원리
.1f는 소수점 한 자리로 반올림하고, >5와 <5는 5칸 안에서 정렬합니다. ,는 천 단위 구분 기호를 넣고, .0%는 분수를 백분율로 보여 줍니다.
값을 변경하고 Python 설치 없이 CodeUtility 온라인 Python 컴파일러에서 실행하세요.
연습 문제
입력값과 경계 조건을 바꾸고 더 큰 데이터에서도 동작을 확인하세요.
- 실행 전에 출력을 예측하세요.
- 빈 입력과 잘못된 입력을 처리하세요.
- 로직을 함수로 만들고 테스트를 추가하세요.
챌린지로 연습하기
이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.
- Multiplication Table Row List the first multiples of a number. 쉬움
- Count Uppercase Letters Count the capital letters in a text. 쉬움
- Initials From a Name Build uppercase initials from a full name. 쉬움