codehaus


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Any better way for this removal?


Use .split() to split the string on the character and then use .join() to rejoin the first 2 tokens

tokens = text.split(?,?)
new_string = ?,?.join(tokens[:2])

On Sat, Nov 7, 2020, at 1:46 PM, Bischoop wrote:
> 
> 
> So I was training with slicing. 
> Came to idea to remove text after second occurence of character, below
> is how I've figured it out, I know if it works it good but.... how you
> guys would made it in more pythonic way?
> 
> text = "This is string, remove text after second comma, to be removed."
> 
> k=  (text.find(",")) #find "," in a string
> m = (text.find(",", k+1)) #Find second "," in a string
> new_string = text[:m]
> 
> print(new_string)
> 
> 
> -- 
> https://mail.python.org/mailman/listinfo/python-list
>