태그된 제품에 대해 수수료를 받습니다.
문자열 포매팅(String formatting)
문자열 내에 변수 또는 표현식을 삽입하여 원하는 형식의 문자열을 만드는 방법
파이썬에서는 다양한 방법으로 문자열 포매팅을 지원한다.
대표적인 방법으로는 % 연산자, str.format() 메서드, 그리고 f-strings (포맷 문자열 리터럴)이 있다.
1. % 연산자
C 스타일의 문자열 포매팅 방식으로, % 기호를 사용하여 변수를 포맷 문자열에 삽입
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string) # 출력: My name is Alice and I am 30 years old.
여기서 %s는 문자열, %d는 정수를 의미
여러 가지 포맷 코드가 있으며, 필요한 형식에 따라 사용한다.
2. str.format() 메서드
str.format() 메서드를 사용하여 포맷팅할 수 있다.
중괄호 {}를 사용하여 문자열 내에 변수를 삽입
name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string) # 출력: My name is Alice and I am 30 years old.
인덱스를 사용하여 순서를 지정하거나, 이름을 사용하여 명확하게 변수를 지정할 수도 있다.
formatted_string = "My name is {0} and I am {1} years old.".format(name, age)
print(formatted_string) # 출력: My name is Alice and I am 30 years old.
formatted_string = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(formatted_string) # 출력: My name is Alice and I am 30 years old.
3. f-strings (포맷 문자열 리터럴)
파이썬 3.6부터 도입된 f-strings는 가장 간단하고 가독성이 좋은 방법
문자열 앞에 f 또는 F를 붙이고, 중괄호 {} 안에 변수 또는 표현식을 삽입
name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string) # 출력: My name is Alice and I am 30 years old.
중괄호 안에 표현식을 넣을 수도 있다.
formatted_string = f"In two years, I will be {age + 2} years old."
print(formatted_string) # 출력: In two years, I will be 32 years old.
4. 고급 포매팅
포맷팅 옵션을 사용하여 출력 형식을 제어할 수 있다.
예를 들어, 소수점 이하 자릿수를 지정하거나, 특정 너비로 정렬할 수 있습니다.
pi = 3.141592653589793
# 소수점 이하 2자리까지 표시
formatted_string = f"Pi to two decimal places: {pi:.2f}"
print(formatted_string) # 출력: Pi to two decimal places: 3.14
# 정렬 및 너비 지정
formatted_string = "{:<10}".format("left") # 왼쪽 정렬
print(formatted_string) # 출력: left
formatted_string = "{:>10}".format("right") # 오른쪽 정렬
print(formatted_string) # 출력: right
formatted_string = "{:^10}".format("center") # 가운데 정렬
print(formatted_string) # 출력: center
이처럼 문자열 포매팅은 다양한 방식으로 수행할 수 있으며, 상황에 맞게 적절한 방법을 선택하면 된다.
f-strings는 최신 파이썬 버전에서 가장 추천되는 방법으로, 간결하고 가독성이 좋다.
관련글
[파이썬] 스트링 컨케트네이션(String concatenation)
스트링 컨케트네이션(String concatenation)두 개 이상의 문자열을 하나의 문자열로 결합하는 작업을 의미파이썬에서는 문자열을 결합할 때 주로 + 연산자를 사용한다.이를 통해 여러 문자열을 이어
gameuiux.tistory.com
태그된 제품에 대해 수수료를 받습니다.