Keep the first word after each comma in a string when there are multiple commas in the string

Viewed 286

Hi I need to remove a word after a separation after each comma. For example, if the first index in a column is

'stack overflow, ask question , keep remove'

(note that they are all in one sting)

I need the output to be,

'stack, ask, keep'

(this is in one string)

so the first word is kept and the rest of words removed after each comma. I used .split but I did not get the result. Here is my approach,

 final_re= [mydf.mycolumn.str.split(' ')[index][0] for index in range(0, len(mydf))]

In this case, it keeps the first word that means if the input is

'stack overflow, ask question , keep remove'

my output would be just

'stack'

however, I need the out put to be

'stack, ask, keep'

I appreciate any suggestion.

2 Answers

This should give you required output

string = 'stack overflow, ask question , keep remove'
', '.join([i.split()[0] for i in string.split(',')])

You could use a regular expression to remove the parts from a string s that you don't need:

import re
res = re.sub(r"(?: .*?)?(, |$)", r"\1", s)
Related