개발부터 자유까지
[Python] 문자열 포맷팅 3가지 방식 본문
목차
Python String Format 3가지 방식
% 포맷팅
% 문자를 사용해서 문자를 포맷팅한다. C언어에서 사용하는 printf 방식과 비슷하다. 파이썬에서는 권장하고 있지 않은 방식이다. 실수할 수 있는 부분이 많고 입력 자료형에 따라서 % 문자 뒤에 붙는 지시자가 다르다.
i = float(input())
print("%f" $ i)
# 입력: 12
# 출력: 12.000000
s = input()
print("%s" % s)
# 입력: water
# 출력: water
s = input()
print("%f" % s)
# 입력: 55
# 출력:
Traceback (most recent call last):
File "D:\toy_project\test\main.py", line 2, in <module>
print("%f" % s)
TypeError: must be real number, not str
위 코드에서 에러난 예시 중에 문자열 형식의 입력을 했을때 포맷 형식이 실수형이기에 에러가 난다.
아래 표처럼 자료형의 타입에 따라 지시자를 다르게 적어줘야 한다.
str.format 함수
공식문서에서 볼 수 있는 내장함수다.
format 안에서 연산도 가능하고, 복수의 값을 다양한 방법으로 전달할 수도 있다.
print("The sum of 1 + 2 is {0}".format(1 + 2))
# 출력: The sum of 1 + 2 is 3
print("I got up at {0}AM before {1} days ago".format(7, 2))
# 출력: I got up at 7AM before 2 days ago
#named indexes:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
# 출력: My name is John, I'm 36
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
# 출력: My name is John, I'm 36
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)
# 출력: My name is John, I'm 36
format 방식에는 고급 문자열 포매팅이 있다.
공백 크기를 지정할 수 있고, 부동소수점에 어디까지 표시할 지를 지정할 수 있다.
{}안에 : 기호를 넣고 그 뒤에 고급 형식지정 문자열을 넣는다. : 뒤에 오는 숫자는 공백의 크기를 뜻한다. <는 값을 앞쪽으로 붙이고 공백을 뒤로 붙인다. >는 값을 뒤쪽으로 붙이고 공백을 앞에 붙인다.
- 정렬
# 전체 10칸을 차지하며 공백을 뒤에 붙임 (문자열을 왼쪽에 붙여서 출력)
print("{:<10} my name is hun".format("hi"))
# 출력: hi my name is hun
# 전체 10칸을 차지하며 공백을 앞에 붙임 (문자열을 오른쪽에 붙여서 출력)
print("{:>10} my name is hun".format("hi"))
# 출력: hi my name is hun
# 전체 10칸을 차지하며 공백을 앞뒤에 붙임 (문자열을 중앙에 붙여서 출력)
print("{:^10} my name is hun".format("hi"))
# 출력: hi my name is hun
- 공백 채우기
# 정렬 후에 "=" 문자로 공백을 채운다
print("{:=^10}".format("happy"))
# 출력:==happy===
# 정렬 후에 var 변수에 할당된 문자로 공백을 채운다
print("{var:=^10}".format(var="zebra"))
# 출력:==zebra===
- 소수점 표현하기
# 부동소수점의 소수점 아래 5자리까지 표시
print("{:10.5f} is result".format(1 / 6))
# 출력: 0.16667 is result
# 천단위로 쉼표 표시
print("{:20,}".format(1234567890))
# 출력: 1,234,567,890
# 총 10자리에서 소수점 아래 4자리까지 표시
print("{:10.4f}".format(7.123456789))
# 출력: 7.1235
* Built-in str.format 공식문서
Built-in Types
The following sections describe the standard types that are built into the interpreter. The principal built-in types are numerics, sequences, mappings, classes, instances and exceptions. Some colle...
docs.python.org
* Format String Syntax 공식문서
string — Common string operations
Source code: Lib/string.py String constants: The constants defined in this module are: Custom String Formatting: The built-in string class provides the ability to do complex variable substitutions ...
docs.python.org
* Formatting types
https://www.w3schools.com/python/ref_string_format.asp
Python String format() Method
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
f-string 포맷팅
파이썬 3.6 버전부터 나온 f-string 포맷팅 방식인데 위 두가지 방식보다 속도가 가장 빠르고 가장 많이 사용하는 방식이다.문자열 앞에 "f" 문자를 붙여서 사용한다.
보통 string 타입과 integer 타입을 같이 출력하려면 str() 함수안에 integer을 넣어서 문자열로 변환시킨 후, "+" 연산자로 붙여서 출력하는데 f-string 방식으로 하면 따옴표 개수를 신경쓰지 않아도 되고 str() 함수를 호출하지 않아도 된다.
# 흔히 사용하는 방식
n = 34
print("I'm " + str(n) + " years old")
# 출력: I'm 34 years old
# f-string 방식
print(f"I'm {n} years old")
# 출력: I'm 34 years old
f-string을 활용한 좋은 연습문제가 있다. 아래를 참고하면 다양한 예제와 이해가 쉬울 것이다.
속도 비교
3가지 문자열 포맷팅 방식이 있는데 마지막 f-string 방식이 가장 빠르다.
간단하게 timeit 모듈을 사용해서 비교해보자.
문자열을 리턴하는 각 함수를 각각 10000번씩 반복하는 실행시간을 출력하는 코드다.
f-string > % 포맷팅 > str.format 순으로 빠르다.
import timeit
order = "1st"
where = "center"
def test1():
return "I am the %s building owner of %s street" % (order, where)
def test2():
return "I am the {0} building owner of {1} street".format(order, where)
def test3():
return f"I am the {order} building owner of {where} street"
t1 = timeit.timeit("test1()", setup="from __main__ import test1", number=10000)
print(t1)
t2 = timeit.timeit("test2()", setup="from __main__ import test2", number=10000)
print(t2)
t3 = timeit.timeit("test3()", setup="from __main__ import test3", number=10000)
print(t3)
# 출력값
# 0.00749990000622347
# 0.010115800017956644
# 0.0034146999823860824
참고 사이트
'Python' 카테고리의 다른 글
[Python] os.walk VS os.listdir 차이점 알아보기 (0) | 2024.01.24 |
---|---|
[Python] websockets 웹소켓 모듈 (0) | 2024.01.18 |
[Python] vscode에서 black formatter 사용하기 (0) | 2024.01.15 |
[Python] miniforge 패키지 설치, 가상환경 설정 (1) | 2024.01.05 |
[Python] alias 명령어로 파이썬 버전 변경하기 (1) | 2024.01.03 |