티스토리 뷰

728x90
반응형

format() 메서드에서는 다양한 형식 옵션을 제공하여 출력 형식을 세밀하게 조정할 수 있습니다. 몇 가지 주요 옵션을 소개합니다.

1. 인덱스 사용하기

중괄호 안에 인덱스를 사용하여 특정 인수를 참조할 수 있습니다.

python

greeting = "My name is {0} and I am {1} years old. {0} lives in New York.".format("Alice", 20)
print(greeting)

2. 키워드 인수 사용하기

format() 메서드는 키워드 인수를 사용하여 값을 지정할 수도 있습니다.

python

greeting = "My name is {name} and I am {age} years old.".format(name="Alice", age=20)
print(greeting)

3. 포맷팅 옵션 사용하기

정수 및 부동 소수점 수에 대해 다양한 형식 옵션을 지정할 수 있습니다.

3.1. 숫자 자리수 지정

python

number = 123.456789
formatted = "The number is {:.2f}".format(number)  # 소수점 이하 2자리
print(formatted)  # 출력: The number is 123.46

3.2. 정수의 천 단위 구분 기호

python

number = 1000000
formatted = "The population is {:,.0f}".format(number)  # 천 단위 구분 기호
print(formatted)  # 출력: The population is 1,000,000

4. 정렬 및 여백 지정

문자열의 정렬 및 여백을 설정할 수 있습니다.

python

# 왼쪽 정렬
left_aligned = "{:<10}".format("test")  # 10칸 중 왼쪽 정렬
print(left_aligned)  # 출력: test      

# 오른쪽 정렬
right_aligned = "{:>10}".format("test")  # 10칸 중 오른쪽 정렬
print(right_aligned)  # 출력:       test

# 가운데 정렬
center_aligned = "{:^10}".format("test")  # 10칸 중 가운데 정렬
print(center_aligned)  # 출력:    test   

5. 포맷팅을 조합하여 사용하기

여러 가지 옵션을 조합하여 사용할 수 있습니다.

python

value = 42.12345
formatted = "Value: {:>10.2f}".format(value)  # 오른쪽 정렬 및 소수점 2자리
print(formatted)  # 출력: Value:      42.12
728x90
반응형