Any better way for this removal?

Tim Chase python.list at tim.thechases.com
Sat Nov 7 11:51:59 EST 2020


On 2020-11-07 13:46, Bischoop wrote:
> 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)

How about:

  new_string = text.rsplit(',', 1)[0]

This also expands to throwing away more than one right-hand bit if
you want:

  from string import ascii_lowercase
  text = ",".join(ascii_lowercase)
  to_throw_away = 5
  new_string = text.rsplit(',', n)[0]

or throwing away `n` left-hand bits too using .split()

  left_portion = text.split(',', n)[-1]

-tkc





More information about the Python-list mailing list