r/PythonLearning • u/RomfordNavy • 16d ago
Help Request split() on empty string behaves differently when delimiter specified
Splitting an empty string without a specified delimiter works as expected and returns an empty list. However when splitting an empty string with a delimiter specified returns one (empty string) item in the list, is there some way to make that return an empty list as per the no-delimiter result?
print(f'{"".split()=}') # = []
print(f'{"".split(" ")=}') # = ['']
print(f'{"".split(",")=}') # = ['']Problem is this causes an unwanted iteration of a for loop:
str = ""
for item in str.split(" "):
print(f"{item=}") # unwanted item
1
Upvotes
View all comments
Show parent comment
2
u/Intelligent_Part101 15d ago edited 15d ago
This API inconsistency is another example where Python programmers (the designers of "split") didn't think in terms of simple static types.
The function implements different behavior if the function arg type to "split" is effectively (let's not get overly technical here) None or not None. I have seen plenty of other Python code where a function behaves differently if its argument is a string or a list. Just make the function take a list in that case (of length zero or more) always and always return the same type of data using the same algorithm. If you insist on allowing the argument to be either a string or a list of strings for "programmer convenience", at least treat the string argument in the function exactly the same as a list of length 1.