본문 바로가기
개발/파이썬

문자열을 결합하는 몇가지 방법

by 장모 2020. 12. 3.

방법 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

 

댓글