You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中拆分字符串并保留空格?

在Python中拆分字符串并保留空格的方法

要实现将字符串拆分为单词与空格交替的列表,有两种实用方法:

方法1:使用正则表达式re.findall()

利用正则匹配规则,可以直接提取所有单词和单个空格:

import re

string = "this is a simple text"
result = re.findall(r'\S+|\s', string)
print(result)
# 输出: ["this", " ", "is", " ", "a", " ", "simple", " ", "text"]

正则表达式\S+匹配一个或多个非空白字符(即单词),\s匹配单个空格,|表示二选一,findall会按字符串顺序返回所有匹配元素。

方法2:手动遍历字符串拆分

如果不想依赖正则库,可以逐个字符处理:

string = "this is a simple text"
result = []
current_word = []

for char in string:
    if char == ' ':
        if current_word:
            result.append(''.join(current_word))
            current_word = []
        result.append(char)
    else:
        current_word.append(char)
# 处理最后一个未加入的单词
if current_word:
    result.append(''.join(current_word))

print(result)
# 输出: ["this", " ", "is", " ", "a", " ", "simple", " ", "text"]

这个逻辑是:用临时列表收集非空格字符,遇到空格时先把收集好的单词加入结果,再添加空格,最后处理末尾剩余的单词。


内容的提问来源于stack exchange,提问作者nofamenoname

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 20:33:15