r/PythonLearning • • 15d 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

10 comments sorted by

5

u/OldAd9280 15d ago edited 13d ago • Bravo

Not directly I don't think, that's fundamentally how str.split is defined to work. 

You could do something like

for item in str.split(" ") if str else []:

2

u/RomfordNavy 15d ago

u/OldAd9280 Thanks that is exactly it.

I tried various attempts to do that myself but couldn't get the syntax right so I, incorrectly, presumed it wasn't possible with a for loop.

3

u/SaltCusp 15d ago

From the docs: If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns [].

Did you know there are docs? https://python-reference.readthedocs.io/en/latest/docs/str/split.html

3

u/Intelligent_Part101 14d ago

That's bad API design. The same algorithm should have been used in both cases (argument or no argument) with the no argument cases having a built-in delimiter value. If they wanted to use a different algorithm in the no org case, that should have been defined as a different function. So readable. /s

1

u/RomfordNavy 14d ago

u/Intelligent_Part101 Couldn't agree more, this is just yet another a blatant inconsistency in Python. Who made such awful design decisions. I had hoped that many such inconsistencies would have been ironed out in version 3 but seemingly not.

2

u/Intelligent_Part101 14d ago edited 14d 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.

1

u/RomfordNavy 14d ago

Python needs a few people with some common sense to get involved in creating a new version which does away with the various inconsistencies and renames some of the obscure function/command names while they are at it.

Maybe they could rename `global` to `module` for a start because it is 'module' level scope after all _not_ 'global'.

1

u/SaltCusp 13d ago

If you want to make it in this world you should look for solutions not problems.

1

u/RomfordNavy 13d ago

u/SaltCusp Which is what we have found in u/OldAd9280 's workaround above. That doesn't change the blatant inconsistency in Python which is something we might hope to get improved in a future version.

2

u/Fluffy_white_fox 9d ago edited 9d ago

you can do

my_str = ""

items = my_str.split(",") if my_str else []

print(items) # Output: []

Or

my_str = ""

items = list(filter(None, my_str.split(",")))

print(items) # Output: []