파이썬 Python 문자열 join 함수

Python join 함수란?

파이썬 문자열 객체에서 사용할 수 있는 메서드로 특정 구분자를 통해서 하나의 문자열로 합칠 때 자주 사용된다. 

사용방법

'구분자'.join(iterable)
  • 구분자는 쉼표(","), 빈 문자열(" "), 줄바꿈("\n")등의 구분자 
  • iterable은 연결할 대상인 리스트, 튜플, 또는 문자열들이 포함된 객체.

1. 리스트 요소 연결하기

items = ["apple", "galaxy", "motorola"]
result = ",".join(items)
print(result) # 출력: apple, galaxy, motorola

result = " ".join(items)
print(result) # 출력: apple galaxy motorola

2. 멀티라인 문자열 생성

lines = ["Line One, Line Two, Line Three"]
text = "\n".join(lines)
print(text) 
# 출력: 
# Line One
# Line Two
# Line Three

3. 파일 경로 생성

folders = ["home", "user", "cookie"]
path = "/".join(folders)
print(path) # 출력: home/user/cookie

주의사항

join()함수는 문자열 리스트에서만 사용 가능.

문자열이 아닌 다른 타입의 요소(int 등) 이 있는 경우 join()으로 합치기 전에 문자열로 변환해야 함.

num = [1, 2, 7]
answer = "".join(map(str,num))
print(answer) # 127

관련 프로그래머스 코테

 

프로그래머스 문자 반복 출력하기

프로그래머스 코딩테스트 문자 반복 출력하기 문제이며, 풀이는 파이썬 Python으로 작성했습니다.https://school.programmers.co.kr/learn/courses/30/lessons/120825문제설명문자열 my_string과 정수 n이 매개변수로

ourjune.tistory.com