one of a kind scene

[list] split과 join 사용 본문

Python/내장모듈 및 자료구조

[list] split과 join 사용

specialscene 2020. 1. 3. 01:25

1. 언제사용?

split은 구분자로 구분된 하나의 문자열(str)을 구분자 기준으로 나누어 list 형태로 만들어 줄때 사용

즉, 자료형이 string list로 바뀌어서 return됨

 

(코드 모양)

문자열.split("구분자")

※구분자 없는 경우(default로 공백을 기준으로 split함) = 문자열.split("")

# split 사례
a = "hello-world"
a = a.split("-")
# 아래와 같은 결과값을 지님
['hello', 'world']

join은 list내의 여러 문자열들을 하나의 문자열로 만들어 줄 때 사용

즉, 자료형이 list  string로 바뀌어서 return됨

 

(코드 모양)

"구분자".join(list or tuple)

※구분자 없이 이어붙이고 싶을때 = "".join(list or tuple)

a = ["1", "2", "3"]
a = list(permutations(a, 2))
# 아래는 permutaion한 a에 alias된 값
[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')]
container = []
for i in a:
	container.append(int("".join(i)))
print(container)
# [12, 13, 21, 23, 31, 32] 이 값들이 print됨