Python 中 join()和 split()函数

Python 中 join()split() 函数详解

join()split() 是 Python 字符串(str) 类的重要方法,分别用于 连接拆分 字符串。它们通常用于字符串处理、数据解析等场景。


1. join() 方法(合并字符串)

join() 方法用于将可迭代对象(如列表、元组)中的多个字符串连接成一个字符串,并用指定的分隔符进行拼接。

语法

'分隔符'.join(可迭代对象)
  • 分隔符:用于连接多个字符串的字符(可以是逗号、空格等)。
  • 可迭代对象:如 listtuple,其中的元素必须是字符串类型。

示例 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(),让字符串处理更加高效!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值