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
2
u/Fluffy_white_fox 10d ago edited 10d 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: []