Python join() 字串合併

join() 方法用來將序列中的元素用指定的字串連接起來。

基本用法

words = ["Hello", "World", "Python"]
result = " ".join(words)
print(result)  # Hello World Python

語法

str.join(iterable)
  • str:用來連接元素的字串
  • iterable:要連接的可迭代物件(元素必須是字串)

不同的連接符號

words = ["apple", "banana", "orange"]

# 空格連接
print(" ".join(words))     # apple banana orange

# 逗號連接
print(",".join(words))     # apple,banana,orange

# 逗號加空格
print(", ".join(words))    # apple, banana, orange

# 換行連接
print("\n".join(words))
# apple
# banana
# orange

# 無間隔連接
print("".join(words))      # applebananaorange

# 自訂分隔符號
print(" | ".join(words))   # apple | banana | orange

連接不同類型的序列

# List
my_list = ["a", "b", "c"]
print("-".join(my_list))  # a-b-c

# Tuple
my_tuple = ("x", "y", "z")
print("-".join(my_tuple))  # x-y-z

# Set(順序不固定)
my_set = {"1", "2", "3"}
print("-".join(my_set))  # 順序可能不同

# 字串(每個字元)
text = "Hello"
print("-".join(text))  # H-e-l-l-o

連接數字

join() 只能連接字串,數字需要先轉換:

numbers = [1, 2, 3, 4, 5]

# 錯誤:數字不能直接 join
# result = ",".join(numbers)  # TypeError

# 正確:先轉換為字串
result = ",".join(str(n) for n in numbers)
print(result)  # 1,2,3,4,5

# 或使用 map
result = ",".join(map(str, numbers))
print(result)  # 1,2,3,4,5

實際範例

建立 CSV 行

data = ["Alice", "25", "Taipei", "Engineer"]
csv_line = ",".join(data)
print(csv_line)  # Alice,25,Taipei,Engineer

建立 URL 路徑

parts = ["users", "123", "profile"]
path = "/".join(parts)
print(f"/{path}")  # /users/123/profile

建立 SQL 查詢

columns = ["name", "age", "city"]
values = ["'Alice'", "25", "'Taipei'"]

sql = f"INSERT INTO users ({', '.join(columns)}) VALUES ({', '.join(values)})"
print(sql)
# INSERT INTO users (name, age, city) VALUES ('Alice', 25, 'Taipei')

建立 HTML 列表

items = ["Python", "JavaScript", "Go"]
html = "<ul>\n" + "\n".join(f"  <li>{item}</li>" for item in items) + "\n</ul>"
print(html)

輸出:

<ul>
  <li>Python</li>
  <li>JavaScript</li>
  <li>Go</li>
</ul>

過濾空字串後連接

parts = ["hello", "", "world", "", "python"]

# 過濾空字串
result = " ".join(filter(None, parts))
print(result)  # hello world python

# 或用 list comprehension
result = " ".join(p for p in parts if p)
print(result)  # hello world python

格式化輸出

# 將數字格式化為電話號碼
digits = "0912345678"
formatted = "-".join([digits[:4], digits[4:7], digits[7:]])
print(formatted)  # 0912-345-678

搭配 split() 使用

# 移除多餘空白
text = "  hello    world   python  "
result = " ".join(text.split())
print(result)  # hello world python

# 替換分隔符號
csv = "a,b,c,d"
tsv = "\t".join(csv.split(","))
print(tsv)  # a	b	c	d

# 反轉單字順序
sentence = "Hello World Python"
reversed_sentence = " ".join(sentence.split()[::-1])
print(reversed_sentence)  # Python World Hello

效能考量

join() 比字串相加 + 更有效率:

# 不好的做法(效率較低)
result = ""
for word in ["a", "b", "c", "d", "e"]:
    result += word + ","

# 好的做法(效率較高)
result = ",".join(["a", "b", "c", "d", "e"])

當連接大量字串時,join() 的效能差異會更明顯。