0
input = '1+2++3+++4++5+6+7++8+9++10'
string = input.split('+')
print(string)

when we run this code the output is ['1', '2', '', '3', '', '', '4', '', '5', '6', '7', '', '8', '9', '', '10']

But i want to split the string with no blank like ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

Is there any function or method to remove blanks without using for loop like

for i in string:
if i == '':
    string.remove(i)
new_be
  • 37
  • 6
  • Very related: [python - Why are empty strings returned in split() results? - Stack Overflow](https://stackoverflow.com/questions/2197451/why-are-empty-strings-returned-in-split-results) , [string - python split without creating blanks - Stack Overflow](https://stackoverflow.com/questions/17542152/python-split-without-creating-blanks) – user202729 Mar 01 '21 at 05:16
  • 2
    Does this answer your question? [How can I split by 1 or more occurrences of a delimiter in Python?](https://stackoverflow.com/questions/2492415/how-can-i-split-by-1-or-more-occurrences-of-a-delimiter-in-python) – Iain Shelvington Mar 01 '21 at 05:18

2 Answers2

3

Generate a list based on the output of split, and only include the elements which are not None

You can achieve this in multiple ways. The cleanest way here would be to use regex.

Regex:

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

List Comprehension:

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']

Loop & Append:

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

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

Simplest way:

customStr="1+2++3+++4++5+6+7++8+9++10"

list( filter( lambda x : x!="" ,customStr.split("+") ) )
Kaustubh J
  • 742
  • 8
  • 9