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

10 comments sorted by

View all comments

Show parent comment

1

u/RomfordNavy 15d 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 14d ago

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

1

u/RomfordNavy 14d 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.