python - 使用 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'
有没有办法在保持单线的同时做到这一点?
谢谢
解决方案
if input: result = input.split("#")
这应该有效。不用加括号!或者,如果您仍然想定义结果:
result = input.split("#") if input else None
推荐阅读
- javascript - reactjs-popup 弹出窗口的自定义样式
- c++ - 从字符串中删除空格不生效
- xcode - Xcode 不会打开任何项目
- wordpress - 我的 wordpress 网站中的社交媒体链接的字体真棒不起作用(出现空白方框)
- state - '在视图更新期间修改状态,这将导致未定义的行为。' 在文本字段上键入时出错 (SwiftUI)
- javascript - 如何访问处理不同输入的数据属性?
- javascript - 如何通过名称获取动画
- html - 如何使用 BeautifulSoup 提取网页“关于我们”下的文本
- import - Vue2 - 导入类、访问和实例化
- reactjs - 如何将动态创建的选项标记为选项列表中使用的选项