
Python에서 문자열에서 변수의 값을 출력하는 방법(string formatting)에는
다음과 같은 세 가지 주요 방법이 있음:
1. % 포맷팅 (%-formatting):
- 공식 명칭: Percent formatting (old-style formatting)
- 도입 버전: Python 초기 버전부터 사용 가능
%연산자(percent, modulo)를 사용하여 문자열에 포함된 형식 지정자를 해당 변수의 값으로 대체.
예: "Hello, %s %s!" % (fname,lname)
2. str.format() 메서드:
- 공식 명칭: str.format()
- 도입 버전: Python 2.6+ 부터 사용 가능
- 이 방법은 중괄호
{}를 사용하여 문자열 내에서 변수를 지정하고,format메서드를 통해 이를 대체.
예: "Hello, {}!".format(name)
3. f-string :
- 공식 명칭: Formatted string literals 또는 f-strings
- 도입 버전: Python 3.6+사용 가능
- f-string은 문자열 앞에
f를 붙이고, 중괄호 내부에 직접 변수 이름을 쓰는 방식.
예: f"Hello, {name}!"
f-string은 가장 최신 방식으로, 가독성과 편리성 측면에서 많은 개발자들에게 선호되고 있으나,
이전 구현 코드(Legacy code)를 읽기 위해서라도 다른 동작방식에 대해서 알고 있어야 함.
같이 보면 좋은 자료들
https://dsaint31.tistory.com/532
[Python] f-String
Python : f-StringPython 3.6 이후 도입됨.기존의 중괄호 {}과 format 메소드를 사용하여 문자열 포매팅을 설정하는 방식(Python 2.6 이후)과 유사하지만, 더 직관적으로 문자열을 포맷팅할 수 있는 기능으로
dsaint31.tistory.com
2025.08.01 - [Python] - str.format() 메서드 - string formatting
str.format() 메서드 - string formatting
str.format() 메소드(format method)를 이용한 string formatting (Python 2.6+).신규 코드 작성의 경우, f-string을 이용하는 경우가 보다 더 권장됨.https://dsaint31.tistory.com/532 [Python] f-StringPython : f-StringPython 3.6 이후
ds31x.tistory.com
2025.07.31 - [Python] - percent(%) formatting
percent(%) formatting
Percent formattingOld Style String Formatting이라고도 불림.파이썬에서 string 내에 variable의 값을 삽입하기 위해 % 연산자를 사용하는 방식.C 언어에서와 매우 유사하기 때문에 "printf-style formatting"이라고도
ds31x.tistory.com
2025.04.02 - [Python] - [Py] print 함수
[Py] print 함수
Python의 print() 함수란?print()는 Python의 built-in 함수로, 표준 출력(stdout) 에 메시지나 데이터를 문자열 형태로 출력하는 기능을 제공. 2024.09.11 - [CE] - [CE] Stream이란 [CE] Stream이란Stream:데이터를 연속적
ds31x.tistory.com
[Python] String : 문자열
String(문자열)이란?다음 URL에서 4.3. String Type을 참고.https://dsaint31.tistory.com/515 [Python] (Data) Type: Summary1. Type 이란?Programming에서 사용되는 모든 value 혹은 object 들의 종류 를 (data) type이라고 부름.수학
ds31x.tistory.com
'Python' 카테고리의 다른 글
| [NumPy] ravel() 메서드 with flatten() 메서드 (0) | 2024.09.09 |
|---|---|
| [NumPy] 생성 및 초기화, 기본 조작 (1) (0) | 2024.09.09 |
| [Python] f-string과 for문 체크 문제 (0) | 2024.09.04 |
| [Python] Class 간단 정리 (0) | 2024.07.24 |
| [Python] 사용자와 상호작용: 입력받기: input, sys.argv and argparse (1) | 2024.07.24 |