split question

A

alexk

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
 
G

Grant Edwards

I've a simple question. Why the following:

words = "123#@$#$@^%[wordA] wordB#@$".split('~`!@#$%^&*()_+-=[]{},./')

doesn't work?

But it does work. Your input string (the one on the left) does
not contain the delimiter string you're passing to the split()
method. The argument to split() is a delimiter string not a
set of delimter characters.
The length of the result vector is 1.

Yup :)
 
M

Michael Spencer

alexk said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,135
Latest member
VeronaShap
Top