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
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']
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
functionisNone, the identity function is assumed, that is, all elements ofiterablethat are false are removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With