방법 1
s = 'message1'
s += 'message2'
s += 'message3'
이해하기 쉽고 작성하기도 편해서 보통 이렇게 사용하지만 문자열은 immutable이라 매번 새로운 문자열이 생성되어 비효율적이다. (물론 대부분의 경우엔 별 문제가 안된다.)
방법 2
그래서 list에 문자열을 넣어준 후 join으로 한 번에 새로운 문자열을 생성한다.
message_list = []
message.append('message1')
message.append('message2')
message.append('message3')
s = ''.join(message_list)
방법 3
StringIO를 사용하는 방법도 있다. 이 경우 방법2보다 더 효율이 좋다. 게다가 tell()로 생성할 문자열의 길이를 중간중간 확인할 수 있는 장점도 있다.
from io import StringIO
sio = String()
sio.write('message1')
sio.tell()
sio.write('message2')
sio.write('message3')
s = sio.getvalue()
대략적으로만 알고 있었는데 이 글을 쓰면서 찾아보니 더 다양한 방법과 수치까지 비교된 글을 찾았다.
https://waymoot.org/home/python_string/
Efficient String Concatenation in Python
Efficient String Concatenation in Python An assessment of the performance of several methods Introduction Building long strings in the Python progamming language can sometimes result in very slow running code. In this article I investigate the computati
waymoot.org
'개발 > 파이썬' 카테고리의 다른 글
파라메터를 정의하는 새로운 방법 (0) | 2020.12.07 |
---|---|
Flask-restx와 webargs에서 TypeError 처리 (0) | 2020.12.07 |
print로 개행 없이 출력 (0) | 2020.02.07 |
SQLAlchemy + MySQL에서 DATETIME에 millisecond 사용 (0) | 2020.01.21 |
파이썬에서 짧은 UUID 생성 (0) | 2020.01.19 |
댓글