← 中文资源

简体中文版本

split() 吞并空白,rsplit 限制切分次数

无参 split() 把连续任意空白当一个分隔符并丢弃首尾;显式给 " " 时连续空格会产出空串。rsplit 加 maxsplit 从右侧只切 N 次,左侧保持完整,正好用来拆扩展名。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

no-arg: ['deploy', 'web.prod', '--wait']
space: ['a', '', 'b']
rsplit: ['app.web.prod', 'internal']
split: ['app', 'web.prod.internal']
stem: report-2026-11-21.final
ext: pdf

实现说明

line、spec、filename 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 直接运行文件,输出会带上标签,比如 no-arg:、space:、rsplit:——输出的每一行都能指回产生它的那次调用。

常见问题

运行时需要 npm、pip、cargo 之类帮忙吗?

不需要——包管理器在这里无事可做,没有任何声明。 文件的状态由几个模块级绑定持有:line、spec、filename。

代码示例

line = "  deploy  web.prod  --wait\n"

# split() with no arguments: any run of whitespace counts as one separator, and leading/trailing whitespace is dropped
print("no-arg:", line.split())

# explicit " " separator: consecutive spaces produce empty strings
print("space:", "a  b".split(" "))

# rsplit cuts from the right and maxsplit caps the count: the left side stays intact
spec = "app.web.prod.internal"
print("rsplit:", spec.rsplit(".", 1))
print("split:", spec.split(".", 1))

# typical use: split the extension off the right side of a filename
filename = "report-2026-11-21.final.pdf"
stem, ext = filename.rsplit(".", 1)
print("stem:", stem)
print("ext:", ext)