0

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?

4
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by seanbp
Featured Replies
  • 1

    [CODE]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 [/CODE] Read More

1
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
0

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 by richieking: n/a

0

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 by seanbp: I forgot to narrate my code.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.