I have these 3 string:

YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs

YELLOW,SMALL,STRETCH,ADULT,Tdsfs

YELLOW,SMALL,STRETCH,ADULT,TD

I would like to remove everything after the last "," including the comma. So i want to remove these parts ",T21fdsfdsfs" ",Tdsfs" and "TD". How could i do that in Python?

products = ["YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs",
            "YELLOW,SMALL,STRETCH,ADULT,Tdsfs",
            "YELLOW,SMALL,STRETCH,ADULT,TD"]

products = [this.rsplit(',',1)[0]
            for this in products
           ]

print products

or this

from __future__ import print_function
products = ["YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs",
            "YELLOW,SMALL,STRETCH,ADULT,Tdsfs",
            "YELLOW,SMALL,STRETCH,ADULT,TD"]
print([this.split(",")[0:-1] for this in products],end="")

##output##
[['YELLOW', 'SMALL', 'STRETCH', 'ADULT'], ['YELLOW', 'SMALL', 'STRETCH', 'ADULT'], ['YELLOW', 'SMALL', 'STRETCH', 'ADULT']]

Edited 6 Years Ago by richieking: n/a

Here's yet another way, without splitting the string. It indexes up to the last comma then copies that string to a new list.

products = ["YELLOW,SMALL,STRETCH,ADULT,T21fdsfdsfs",
            "YELLOW,SMALL,STRETCH,ADULT,Tdsfs",
            "YELLOW,SMALL,STRETCH,ADULT,TD"]

products2 = []

for i in products: 
    products2.append(i[:i.rfind(',')])

print(products)
print(products2)

Edited 5 Years Ago by seanbp: I forgot to narrate my code.

This question has already been answered. Start a new discussion instead.