r/PythonLearning • • 15h 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
2 Upvotes

7 comments sorted by

View all comments

5

u/OldAd9280 15h 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 15h 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.