[Python] split() 함수 vs. join() 함수
알고리즘 공부하면서 알게 된 join() 함수.
split() 과 비교하면서 공부하면서 좋을 거 같아 정리.
split() 함수
string.split(separator, maxsplit)
split() 함수는 string을 list로 분할해주는 함수.
separator character를 기준으로 분할된다. separator의 디폴트 값은 공백(whitespace)
maxsplit에는 분할할 개수 지정
split() 사용예시
txt = "mango$blueberry$kiwi$melon"
x = txt.split('$',1)
print(x)
$ 기준으로 분할하고 1번만 분할하라는 뜻
1번만 분할되어 2개의 element로 쪼개진 걸 확인 할 수 있다.
join() 함수
string.join(iterable)
join()은 iterable의 elements를 조인하고 결합된 string을 반환하는 함수.
join()은 iterable의 모든 element를 결합.
join() 사용예시
myDict = {"name": "John", "country": "Canada"}
x = "&".join(myDict)
print(x)
dict도 iterable이라서 join 가능
키값에 &가 붙여서 나오는 걸 확인할 수 있다.
split(), join() 응용
org = "HI, I am from korea"
words = org.split()
print(words)
sentence = ' '.join(words)
print(sentence)
공백 기준으로 분할하고, 공백을 추가하면서 join
org = "HI-I-am-from-korea"
words = org.split('-')
print(words)
sentence = '-'.join(words)
print(sentence)
- 기준으로 split하고 -을 추가하면서 join
Reference
Python String join() 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
Python String split() 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