split question
Michael Spencer
spencermah at comcast.net
Thu Apr 28 13:17:38 EDT 2005
alexk wrote:
> I've a simple question. Why the following:
>
> words = "123#@$#$@^%[wordA] wordB#@$".split('~`!@#$%^&*()_+-=[]{},./')
>
> doesn't work? The length of the result vector is 1.
>
> I'm using ActivePython 2.4
>
> Alex
>
Do you mean, why doesn't it split on every character in '~`!@#$%^&*()_+-=[]{},./' ?
Help on built-in function split:
split(...)
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator.
sep as a whole is the delimeter string
If you want to split on any of the characters in your sep string, use a regexp:
Perhaps:
>>> import re
>>> splitter = re.compile("[\[\]~`!@#$%^&*()_+-= ]+") #note escapes for []
>>> splitter.split("123#@$#$@^%[wordA] wordB#@$")
['', 'wordA', 'wordB', '']
>>>
is closer to what you had in mind
Michael
More information about the Python-list
mailing list