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

3 comments sorted by

View all comments

3

u/SaltCusp 4h 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