Whitespace test after string.split

Peter Otten __peter__ at web.de
Sat Nov 26 10:15:17 EST 2005


David Pratt wrote:

> Hi.  I am splitting a string on a non whitespace character. One or more
> whitespace characters can be returned as items in the list. I do not
> want the items in the list that are only whitespace (can be one or more
> characters of whitespace) and plan to use string.strip on those items
> that are not only whitespace (to remove any whitespace from front or
> back of items).
> 
> What kind of efficient test can I use to obtain only list items
> returned from the split that I am interested in, ignoring any list
> items that would only be comprised of one or more characters of
> whitespace (since whitespace can mean one or more spaces, tabs, and
> other characters)

>>> s = "alpha, \t\n, gamma, delta,"
>>> s.split(",")
['alpha', ' \t\n', ' gamma', ' delta', '']
>>> [t for t in s.split(",") if not t.isspace()]
['alpha', ' gamma', ' delta', '']
>>> [t for t in s.split(",") if t and not t.isspace()]
['alpha', ' gamma', ' delta']
>>> [t.strip() for t in s.split(",") if t and not t.isspace()]
['alpha', 'gamma', 'delta']

There you are.

> As a second question, I am seeing string split as deprecated in 2.4.2
> manual.  What is planned in future to split (strings or unicode)?

Just use the corresponding methods, e. g. s.strip() instead of
string.strip(s) etc.

Peter




More information about the Python-list mailing list