Python removal in line

I have these 3 lines:

YELLOW, SMALL, STRETCH, ADULT, T21fdsfdsfs
YELLOW, SMALL, STRETCH, ADULT, Tdsfs
YELLOW, SMALL, STRETCH, ADULT, TD

I would like to delete everything after the last ,, including the comma. Therefore, I want to remove these parts ,T21fdsfdsfs, ,Tdsfsand TD. How can I do this in Python?

+3
source share
4 answers

You can not. Create a new line with the fragments you want to keep.

','.join(s.split(',')[:4])
+6
source
s.rsplit(',', 1)[0]

In any case, I suggest taking a look at the Ignacio Vasquez-Abrams answer , this may make more sense for your problem.

+5

Zen of Python:

- - .

... , rpartition:

>>> for item in catalogue:
...     print item.rpartition(',')[0]
... 
YELLOW,SMALL,STRETCH,ADULT
YELLOW,SMALL,STRETCH,ADULT
YELLOW,SMALL,STRETCH,ADULT

.

+3
source

If you reference elements string, you can use str.rsplit()to separate each line by setting maxsplitto 1.

str.rsplit([sep[, maxsplit]])

Returns a list of words in a string, using sep as the delimiter string. If maxsplit is specified, the maximum maxsplit is executed, the rightmost ones. If sep is not specified or None, any line of spaces is a delimiter. Except for the separation on the right, rsplit () behaves like split (), which is described in detail below.

>>> lst = "YELLOW,SMALL,STRETCH,ADULT,T"
>>> lst.rsplit(',',1)[0]
'YELLOW,SMALL,STRETCH,ADULT'
>>> 
0
source

Source: https://habr.com/ru/post/1778564/


All Articles