1

Here is my code:

def split_string(source,splitlist):
    sl = list(splitlist)
    new = source.split(sl)
    return new

When i run it:

print split_string("This is a test-of the,string separation-code!"," ,!-")

I have the following error:

new = source.split(sl)
TypeError: expected a character buffer object

How can I fix this?

Note: first i want to make a list from splitlist than i want split source with every element in my sl list.

Thanks.

Michael
  • 15,386
  • 36
  • 94
  • 143
  • possible duplicate of [Python strings split with multiple separators](http://stackoverflow.com/questions/1059559/python-strings-split-with-multiple-separators) – ilent2 Sep 16 '13 at 14:56

3 Answers3

2

The argument to str.split must be a string, not a list of possible separators.

chepner
  • 497,756
  • 71
  • 530
  • 681
1

I guess you're looking for something like

import re
def multisplit(s, delims):
    delims = '|'.join(re.escape(x) for x in delims)
    return re.split(delims, s)

print multisplit('a.b-c!d', '.-!') # ['a', 'b', 'c', 'd']

str.split doesn't accept a list of separators, although I wish it did, just like endswith.

georg
  • 211,518
  • 52
  • 313
  • 390
0

With no additional libraries you could do:

def split_string(source,splitlist):
    ss = list(source)
    sl = list(splitlist)
    new = ''.join([o if not o in sl else ' ' for o in ss]).split()
    return new
ilent2
  • 5,171
  • 3
  • 21
  • 30