Skip to content

Python split ignore empty | How to ignore empty spaces – Example code

  • by

Splitting a string can sometimes give empty strings returned in the Python split() method.

For example, how Python split method to return list with empty space.

str1 = '/segment/segment/'.split('/')

print(str1)

Output:

Python split ignore empty

More generally, to remove empty strings returned in split() results, you may want to look at the filter function.

f = filter(None, '/segment/segment/'.split('/'))
s_all = list(f)
print(s_all)

Output: [‘segment’, ‘segment’]

How to Python split ignore the empty example

Python simple example code. As per upper code, it was only one type of problem but in real-time there can be more.

Method 1: Example Remove all Empty Strings From the List using List Comprehension

import re

s = '--hello-world_how    are\tyou-----------today\t'
words = re.split('[-_\s]+', s)
print(words)

words = [x for x in words if x != '']
print(words)

Output:

Remove all Empty Strings From the List using List Comprehension

Method 2: Example Remove all Empty Strings From the List using filter()

import re

s = '--hello-world_how    are\tyou-----------today\t'
words = re.split('[-_\s]+', s)
words = list(filter(bool, words))
print(words)

Method 3: Example use re.findall() Instead

import re

s = '--hello-world_how    are\tyou-----------today\t'
words = re.findall('([^-_\s]+)', s)
print(words)

Do comment if you have any doubts and suggestions on this Python split topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *