【问题标题】:how can i split string with no blank?如何拆分没有空格的字符串?
【发布时间】:2021-03-01 05:13:49
【问题描述】:
input = '1+2++3+++4++5+6+7++8+9++10'
string = input.split('+')
print(string)

当我们运行这段代码时,输​​出是['1', '2', '', '3', '', '', '4', '', '5', '6', '7', '', '8', '9', '', '10']

但我想分割字符串,没有空格,如['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

有没有什么功能或方法可以在不使用for循环的情况下删除空格

for i in string:
if i == '':
    string.remove(i)

【问题讨论】:

标签: python python-3.x


【解决方案1】:

根据split的输出生成list,只包含不是None的元素

您可以通过多种方式实现这一目标。这里最干净的方法是使用regex

正则表达式:

import re
re.split('\++', inp)
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

列表理解:

inp = '1+2++3+++4++5+6+7++8+9++10'
[s for s in inp.split('+') if s]
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

循环和追加:

result = []
for s in inp.split('+'):
    if s:
        result.append(s)

result
#['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

【讨论】:

    【解决方案2】:

    最简单的方法:

    customStr="1+2++3+++4++5+6+7++8+9++10"
    
    list( filter( lambda x : x!="" ,customStr.split("+") ) )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 2021-08-11
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多