Python 복습 (5) : format 메서드

STUDY_J·2024년 7월 13일

format

  • Python의 format 메서드는 문자열 포맷팅을 위한 강력하고 유연한 방법을 제공합니다.
    중괄호 {}를 사용하여 문자열 내에 변수나 표현식을 삽입할 수 있습니다.
s = "Alice"
a = 30
h = 165.5

print("Name: {}, Age: {}, Height: {}".format(s, a, h))  
# Name: Alice, Age: 30, Height: 165.5

중괄호 {} 안에 인덱스를 사용하여 값을 참조할 수도 있다

s = "Alice"
a = 30
h = 165.5

print("Name: {0}, Age: {1}, Height: {2}".format(s, a, h))  
# Name: Alice, Age: 30, Height: 165.5
print("Height: {2}, Name: {0}, Age: {1}".format(s, a, h))  
# Height: 165.5, Name: Alice, Age: 30

변수명을 사용하는 방법

중괄호 안에 변수명을 사용하여 값을 참조할 수도 있습니다.

print("Name: {name}, Age: {age}, Height: {height}".format(name="Alice", age=30, height=165.5))  
# Name: Alice, Age: 30, Height: 165.5

실수형 포맷팅

format 메서드를 사용하여 실수형 데이터를 포맷팅할 때 소수점 이하 자릿수를 지정할 수 있습니다.

{:.nf}: 소수점 이하 n자리까지 출력
{:.mf}: 전체 m자리 중 소수점 이하 n자리까지 출력

pi = 3.141592653589793

# 소수점 이하 2자리까지 출력
print("Value of Pi: {:.2f}".format(pi))  # Value of Pi: 3.14

# 소수점 이하 5자리까지 출력
print("Value of Pi: {:.5f}".format(pi))  # Value of Pi: 3.14159

# 전체 8자리 중 소수점 이하 3자리까지 출력
print("Value of Pi: {:8.3f}".format(pi))  # Value of Pi:    3.142

# 전체 10자리 중 소수점 이하 4자리까지 출력
print("Value of Pi: {:10.4f}".format(pi))  # Value of Pi:     3.1416

0개의 댓글