0

I want to do something to the effect of:

x = [" ","cats"]
def function(a):
     a.split([any of the elements in x])
     return a

How would I make Python accept any of the elements in x as an argument (so it splits as spaces and cats)?

Edit: Sorry, I should have probably specified: a is expected to be a list

(I'm really, really sorry for not being clear.)

input - a = "I love cats so much" expected output - ["I" , "love","so" , "much"]

Basically, I want it to perform the split function for " " and then for "cats".

V__M
  • 21
  • 4
  • 1
    split is a string method and not available for integers as in `x`. – too honest for this site Apr 27 '15 at 01:39
  • Do you want it to look like this? [' ','c','a','t','s']? As in you split the elements of the strings up, and return a collectively split string? Please give an example of what you are intending to do. – ProfOak Apr 27 '15 at 01:45
  • Please edit your question to have examples of expected input and output beahvior. As it is I have no clue what you want. – Mark Tolonen Apr 27 '15 at 01:47
  • Ok, you edited, but what exactly do you mean by "split" then? The string-method "split" would return an empty list for " " and does not change `x[1]`. Please define exactly(!) what split actually should do and provide an example for a. Also, a sample result would be very helpful. – too honest for this site Apr 27 '15 at 01:49
  • In another comment, you wrote you wanted to remove "cats", not split actually. It would really be helpful to get the question clear before asking- – too honest for this site Apr 27 '15 at 02:00

3 Answers3

0
s = "I love cats so much"
x = [" ", "cats"]

for delim in x:
    s = s.replace(delim, " ")

print s.split()

You're making a new list, without any of the cats.

ProfOak
  • 541
  • 4
  • 10
0

Here's one way. Not the most readable of approaches but gets the job done.

import re
x = [" ", "cats"]
pattern = "|".join(x)

re.split(pattern, "I love cats very much")
Noufal Ibrahim
  • 71,383
  • 13
  • 135
  • 169
0
def split_many(s, *words):
    return filter(bool, reduce(lambda s, word: 
            s.replace(word, words[0]), words, s).split(words[0]))

print split_many('I love cats so much', 'cats', ' ')
Juan Lopes
  • 10,143
  • 2
  • 25
  • 44