I need to split a string. I am using this:
def ParseStringFile(string):
p = re.compile('\W+')
result = p.split(string)
But I have an error: my result has two empty strings (''), one before 'Лев'. How do I get rid of them?
As nhahtdh pointed out, the empty string is expected since there's a \n
at the start and end of the string, but if they bother you, you can filter
them very quickly and efficiently.
>>> filter(None, ['', 'text', 'more text', ''])
['text', 'more text']
filter
usually takes a callable function as first argument and creates a list with all elements removed for which function(element)
returns False
. Here None
is given, which triggers a special case: The element is removed if bool(element)
is false. As bool('')
is false, it gets removed.
Also see the manual.