Search code examples
pythonlistpython-re

why length of empty list is not 0 in re.split


import re
a=''
b=re.split(" |,",a)
print(b)
print(len(b))
print(type(b))

why len(b) is 1 instead of 0, but indeed b is empty list,and I cannot find any explanations in python re doc


Solution

  • b is not the empty list. It is a list with an empty string.

    The rule is that split returns 1 more element than there are (non-overlapping) occurrences of the separator in the string. So when there is one occurrence of the separator, you'll get a list of two strings. If there are zero occurrences, you'll get a list with one string.