首页 > 解决方案 > 使用 str.split 构建带有“单行 for”的字符串列表

问题描述

这似乎是一个非常基本的问题,但我找不到答案。

我正在尝试从更大的字符串上的拆分构建字符串列表。

input = 'I#have#a#problem'
result = [s for s in input.split('#')]
>>> ['I', 'have', 'a', 'problem']

这完美无缺。问题是,有时输入不是字符串,而是无。为了避免 python 错误AttributeError: AttributeError: 'NoneType' object has no attribute 'split',我尝试添加一条if语句,但这并不能防止错误发生。

input = None
result = [s for s in input.split('#') if input]
>>> AttributeError: 'NoneType' object has no attribute 'split'

有没有办法在保持单线的同时做到这一点?

谢谢

标签: python

解决方案


if input: result = input.split("#")

这应该有效。不用加括号!或者,如果您仍然想定义结果:

result = input.split("#") if input else None

推荐阅读