Python 中 join()
和 split()
函数详解
join()
和 split()
是 Python 字符串(str) 类的重要方法,分别用于 连接 和 拆分 字符串。它们通常用于字符串处理、数据解析等场景。
1. join()
方法(合并字符串)
join()
方法用于将可迭代对象(如列表、元组)中的多个字符串连接成一个字符串,并用指定的分隔符进行拼接。
语法
'分隔符'.join(可迭代对象)
分隔符
:用于连接多个字符串的字符(可以是逗号、空格等)。可迭代对象
:如list
、tuple
,其中的元素必须是字符串类型。
示例 1:使用逗号连接列表中的字符串
words = ["apple", "banana", "cherry"]
result = ", ".join(words)
print(result) # "apple, banana, cherry"
示例 2:使用空格连接
words = ["Hello", "World"]
result = " ".join(words)
print(result) # "Hello World"
示例 3:使用 -
连接元组中的字符串
tuple_words = ("Python", "is", "awesome")
result = "-".join(tuple_words)
print(result) # "Python-is-awesome"
示例 4:使用 join()
处理字符串
text = "ABC"
result = "*".join(text)
print(result) # "A*B*C"
示例 5:连接数字列表(错误示例)
numbers = [1, 2, 3]
# print(",".join(numbers)) # ❌ 会报错:TypeError: sequence item 0: expected str instance, int found
解决方案:先将数字转换为字符串
numbers = [1, 2, 3]
result = ",".join(map(str, numbers))
print(result) # "1,2,3"
2. split()
方法(拆分字符串)
split()
方法用于将字符串拆分为列表,默认以空格为分隔符。
语法
str.split(sep=None, maxsplit=-1)
sep
(可选):指定分隔符(默认是空格)。maxsplit
(可选):最大拆分次数,默认为-1
(即不限制)。
示例 1:按空格拆分字符串
text = "Hello World Python"
result = text.split()
print(result) # ['Hello', 'World', 'Python']
示例 2:按逗号拆分
text = "apple,banana,cherry"
result = text.split(",")
print(result) # ['apple', 'banana', 'cherry']
示例 3:按 -
拆分
text = "2024-02-22"
result = text.split("-")
print(result) # ['2024', '02', '22']
示例 4:限制拆分次数
text = "apple,banana,cherry,grape"
result = text.split(",", maxsplit=2)
print(result) # ['apple', 'banana', 'cherry,grape']
示例 5:去掉多余空格
text = " Hello World Python "
result = text.split()
print(result) # ['Hello', 'World', 'Python']
3. join()
和 split()
结合使用
text = "apple banana cherry"
words = text.split() # 拆分成列表
new_text = "-".join(words) # 重新拼接
print(new_text) # "apple-banana-cherry"
4. join()
vs. split()
对比
方法 | 作用 | 示例 |
---|---|---|
join() | 连接多个字符串 | "-".join(["a", "b", "c"]) → "a-b-c" |
split() | 拆分字符串 | "a-b-c".split("-") → ["a", "b", "c"] |
📌 总结
join()
负责 合并字符串,用于列表 → 字符串。split()
负责 拆分字符串,用于字符串 → 列表。join()
只能用于字符串,split()
适用于任何字符串分隔处理。
掌握 join()
和 split()
,让字符串处理更加高效!