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']]

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)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.