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

Python:拆分列表中以空格分隔的字符串问题求助

解决Python列表字符串拆分问题

嘿,别担心!作为Python新手遇到这种小困扰太正常啦😉,其实用Python自带的字符串方法就能轻松搞定你的需求。

核心方法:split()

Python的字符串split()方法默认会按任意空白字符(包括单个空格、多个连续空格、制表符等)拆分字符串,而且会自动忽略字符串首尾的空白,完全适配你的场景。

具体实现代码

首先是最直观的分步写法,适合新手理解:

# 你的原始列表
mylist = ["a word 1 2 3 4","b word 5 6 7 8"]

# 拆分第一个字符串到newlist1
newlist1 = mylist[0].split()
# 拆分第二个字符串到newlist2
newlist2 = mylist[1].split()

# 验证结果
print(newlist1)  # 输出: ['a', 'word', '1', '2', '3', '4']
print(newlist2)  # 输出: ['b', 'word', '5', '6', '7', '8']

如果你想更简洁,一行代码就能完成:

mylist = ["a word 1 2 3 4","b word 5 6 7 8"]
newlist1, newlist2 = [s.split() for s in mylist]

这里用了列表推导式,遍历原列表的每个字符串,调用split()拆分后,直接解包到两个新列表里。

小补充

如果以后遇到其他分隔符(比如逗号、分号),只需要给split()传对应的参数就行,比如split(',')会按逗号拆分字符串。但你的场景用默认的无参split()就刚好合适~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:36:01