简体   繁体   中英

how can i split string with no blank?

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)

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

Simplest way:

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

list( filter( lambda x : x!="" ,customStr.split("+") ) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM