Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a split function that returns [] in this case?

Tags:

python

list

split

Of course we have:

"1,2,3".split(",")  # ["1", "2", "3"]
"1".split(",")      # ["1"]

but also this, which is sometimes problematic in some situations (*):

"".split(",")       # [""]

Is there a built-in way (maybe with a parameter, or a specific function) to have:

"".split(",", allow_empty=True)       # []

?

This would (sometimes) make sense: the input is empty, so the output list should be empty.

(*) Example situation:

for element in s.split(","):
    print(f"we have the element {element}")

# works for s = "1, 2, 3"
# works for s = "1"
# doesn't work for s = ""  => the loop should be empty
like image 735
Basj Avatar asked Feb 27 '26 13:02

Basj


2 Answers

Not to my knowledge but you could use a regex with re.findall:

import re

re.findall(r'[^,]+', '1,2,3')
# ['1', '2', '3']

re.findall(r'[^,]+', '1')
# ['1']

re.findall(r'[^,]+', '')
# []

Note that this would also discard empty strings within the input string:

re.findall(r'[^,]+', '1,,3')
# ['1', '3']
like image 156
mozway Avatar answered Mar 01 '26 01:03

mozway


To ensure non-empty iterator (for looping) you can rely on filter builtin function:

s = "" 
for element in filter(None, s.split(",")):
    print(f"we have the element {element}")

# nothing is printed

From filter(function, iterable) doc:

If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

like image 24
RomanPerekhrest Avatar answered Mar 01 '26 03:03

RomanPerekhrest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!