0

I just got introduced to the re module and I learnt that it could be used to split strings very well. Then I wrote the following code:

import re
print(re.split(r'[a-f]','abcdefghtuyi op re the'))

I expected that Python would return:

['ghtuyi op r', ' th',] # as all the alphabets from a to f are expected to be sliced

But it returned:

['' '', '', '', '', '', 'ghtuyi op r', ' th', '']

Why are these blank list objects appearing?

Also, I did take a look at this question: Why are empty strings returned in split() results? but it has nothing to do with re. How do I get rid of these blank objects while using the re module?

poke
  • 369,085
  • 72
  • 557
  • 602
Ron.W
  • 3
  • 2
  • 1
    Consider this: `*a*b*c*d*e*f*ghtuyi op r*e* th*e*` – I put a star in every place that the original string will be split at by splitting it on any letter `a-f`. The split letters themselves are not included, so you get a lot of blank results there. – poke Jul 19 '17 at 11:55
  • This was answered already in the other question but in general if you want to get rid of empty strings in a list you could easily do: new_list = [] for element in old_list: if element != "": new_list.append(element) #(with the right indentation) – BourbonCreams Jul 19 '17 at 12:03

0 Answers0