0

New to python and looking for help.

output = []

mylist = ['LionRed 1','TigerWhite 2','BearBlue 3']

for item in mylist:  
    tempitem = item.split("Red")[0]  
    output.append(tempitem)

The output of this is ['Lion', 'TigerWhite 2', 'BearBlue 3'] which is what I want BUT I'd like to add two more splits - "White" and "Blue" to get the output ['Lion', 'Tiger', 'Bear'].

Francisco
  • 10,918
  • 6
  • 34
  • 45
  • Are you pretty much looking to just get the first word of every string before an upper case letter is seen? So is that pretty much how all your strings will look like? – idjaw Nov 04 '16 at 03:16
  • What if you had `Lion123Red 1`. What should the result be? – idjaw Nov 04 '16 at 03:20
  • I would get Lion123 in this example which is fine. Just trying to remove everything after 'Red' – Adam Silverman Nov 04 '16 at 03:21
  • I want to add item.split("White")[0] and item.split("Blue")[0] to get ['Lion', 'Tiger', 'Bear']. I just dont know how to add that to the loop – Adam Silverman Nov 04 '16 at 03:23

3 Answers3

0

Not sure what you mean by specified characters, I assume your want to filter based on the color words.

>>> mylist = ['LionRed 1','TigerWhite 2','BearBlue 3']
>>> filter_list = ['Red', 'White', 'Blue']
>>> output = [item.split(filter_word)[0] for (item,filter_word) in zip(mylist,filter_list)]
>>> output
['Lion', 'Tiger', 'Bear']
W.Zhao
  • 34
  • 3
  • Wouldn't this mean you have to hardcode your filtered list? – Apoorv Kansal Nov 04 '16 at 03:26
  • I think this is what im looking for. I just wanted to specific which characters or words (in this case, "Red", "White", "Blue") and remove everything after that in the string. Looks like I just need to create a list of words to search by. Ill give this a shot. – Adam Silverman Nov 04 '16 at 03:30
  • I don't know what Adam mean by 'specified characters'. He needs to better clarify his question, like the pattern of the mylist and filter condition. – W.Zhao Nov 04 '16 at 03:36
  • W.Zhao - I want to remove a part of a string that starts at the "specified character". "Specified character" = each item in the filtered_list you provided. – Adam Silverman Nov 04 '16 at 03:48
0

Assumption: You want the first word out of each list (correct me if I am wrong)

import re
mylist = ['LionRed 1','TigerWhite 2','BearBlue 3']
output = [re.findall(r'.*(?=[A-Z])',a)[0] for a in mylist]

OUTPUT:

['Lion', 'Tiger', 'Bear']
Apoorv Kansal
  • 3,210
  • 6
  • 27
  • 37
0

You can use the built-in str.rsplit or check out this question.

Community
  • 1
  • 1