分割函数(Split Function)
分割函数通常用于将一个字符串按照指定的分隔符拆分成多个部分,并返回一个列表。在 Python 中,split()
是字符串的内置方法,用于实现这一功能。
1. str.split()
基本用法
语法
str.split(sep=None, maxsplit=-1)
- **
sep
**:分隔符(默认为所有空白字符,如空格、换行\n
、制表符\t
)。 - **
maxsplit
**:最大分割次数(默认-1
,表示不限制)。
示例
text = "Hello World Python"
words = text.split() # 默认按空格分割
print(words) # ['Hello', 'World', 'Python']
2. 指定分隔符
可以传入 sep
参数来指定分割方式:
csv = "apple,banana,orange"
fruits = csv.split(",") # 按逗号分割
print(fruits) # ['apple', 'banana', 'orange']
3. 限制分割次数(maxsplit
)
text = "one two three four"
parts = text.split(maxsplit=2) # 只分割前两次
print(parts) # ['one', 'two', 'three four']
4. 处理连续分隔符
如果分隔符连续出现,默认会返回空字符串:
text = "a,,b,,c"
parts = text.split(",")
print(parts) # ['a', '', 'b', '', 'c']
如果想去掉空字符串,可以结合 filter
:
parts = list(filter(None, text.split(",")))
print(parts) # ['a', 'b', 'c']
5. rsplit()
从右分割
rsplit()
从字符串的右侧开始分割:
text = "one two three four"
parts = text.rsplit(maxsplit=1) # 从右侧分割一次
print(parts) # ['one two three', 'four']
6. 按行分割(splitlines()
)
splitlines()
可以按换行符 \n
分割:
text = "Line1\nLine2\nLine3"
lines = text.splitlines()
print(lines) # ['Line1', 'Line2', 'Line3']
7. 正则表达式分割(re.split()
)
如果需要更复杂的分割规则,可以使用 re.split()
:
import retext = "apple123banana456orange"
parts = re.split(r"\d+", text) # 按数字分割
print(parts) # ['apple', 'banana', 'orange']
8. 自定义分割函数
如果 split()
不能满足需求,可以自己实现分割逻辑:
def custom_split(s, sep):parts = []current = ""for char in s:if char == sep:parts.append(current)current = ""else:current += charif current: # 添加最后一个部分parts.append(current)return partstext = "a,b,c"
print(custom_split(text, ",")) # ['a', 'b', 'c']
总结
方法 | 说明 | 示例 |
---|---|---|
split() | 默认按空格分割 | "a b c".split() → ['a', 'b', 'c'] |
split(sep) | 按指定分隔符分割 | "a,b,c".split(",") → ['a', 'b', 'c'] |
split(maxsplit=n) | 限制分割次数 | "a b c d".split(maxsplit=2) → ['a', 'b', 'c d'] |
rsplit() | 从右侧分割 | "a b c".rsplit(maxsplit=1) → ['a b', 'c'] |
splitlines() | 按行分割 | "a\nb\nc".splitlines() → ['a', 'b', 'c'] |
re.split() | 正则表达式分割 | re.split(r"\d+", "a1b2c") → ['a', 'b', 'c'] |
常见问题
-
**
split()
和split(" ")
的区别?**split()
会合并连续空白字符,而split(" ")
不会:"a b".split() # ['a', 'b'] "a b".split(" ") # ['a', '', 'b']
-
如何去掉分割后的空字符串?
- 使用
filter(None, parts)
或列表推导式:parts = [x for x in text.split(",") if x]
- 使用
-
如何分割字符串但保留分隔符?
- 使用
re.split()
并捕获分组:re.split(r"([,;])", "a,b;c") # ['a', ',', 'b', ';', 'c']
- 使用