Python 字符串分隔
str.split(sep=None, maxsplit=-1) 将字符串分隔为列表。
按空白字符分隔
不指定 sep 时,连续的空白字符会被视为一个分隔区域,字符串开头和结尾的空白不会产生空元素:
text = " this is\tstring\nexample "
print(text.split())
# ['this', 'is', 'string', 'example']指定分隔符
text = "this is string example"
print(text.split(" "))
# ['this', 'is', 'string', 'example']
print(text.split(" ", 1))
# ['this', 'is string example']
print(text.split("s"))
# ['thi', ' i', ' ', 'tring example']指定 sep 后,连续分隔符会产生空字符串:
print("a,,b".split(","))
# ['a', '', 'b']从右侧限制分隔次数
需要优先从右侧分隔时使用 rsplit():
path = "archive.2026.07.zip"
name, extension = path.rsplit(".", 1)
print(name)
# archive.2026.07