.join() 완벽 정리.join()은 문자열 리스트를 하나의 문자열로 합칠 때 사용하는 메서드.
words = ["Hello", "World"]
result = " ".join(words) # 띄어쓰기로 연결
print(result) # "Hello World"
" " → 리스트의 요소들을 공백으로 연결"".join(...) → 빈 문자열로 연결 가능words = ["apple", "banana", "cherry"]
print(", ".join(words)) # "apple, banana, cherry"
print("-".join(words)) # "apple-banana-cherry"
print("".join(words)) # "applebananacherry" (구분자 없음)
numbers = [1, 2, 3]
result = "-".join(map(str, numbers))
print(result) # "1-2-3"
join()할 수 없음!map(str, numbers)를 사용해서 문자열로 변환 후 join()\n)로 합쳐 여러 줄 출력lines = ["First line", "Second line", "Third line"]
result = "\n".join(lines)
print(result)
출력
First line
Second line
Third line
\n을 활용하면 여러 줄 문자열 생성 가능join() 가능words = ("red", "green", "blue")
result = " | ".join(words)
print(result) # "red | green | blue"
join() 불가)numbers = [1, 2, 3]
print("".join(numbers)) # ❌ TypeError 발생!
해결 방법
print("".join(map(str, numbers))) # "123" ✅
split()과 함께 활용s = "apple,banana,cherry"
words = s.split(",") # ["apple", "banana", "cherry"]
result = "-".join(words) # "apple-banana-cherry"
split()으로 나눈 후 join()으로 다시 합칠 수 있음.| 메서드 | 설명 | 예제 |
|---|---|---|
"구분자".join(리스트) | 리스트를 문자열로 변환 | ", ".join(["a", "b"]) → "a, b" |
"".join(리스트) | 구분자 없이 합치기 | "".join(["a", "b"]) → "ab" |
"\n".join(리스트) | 여러 줄 문자열 만들기 | "\n".join(["a", "b"]) → "a\nb" |
"".join(map(str, 숫자리스트)) | 숫자 리스트 연결 | "".join(map(str, [1, 2, 3])) → "123" |
.join()은 문자열 합치기 최적화된 방법이므로 + 연산보다 효율적! 🚀