codehaus


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

Any better way for this removal?


>
>
> On Sat, Nov 7, 2020 at 8:51 AM Bischoop <Bischoop at vimart.net> 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
>
>
Not sure what's more Pythonic, but another way of doing it would be to use
`m = text.split(",", 2)`, then rejoin the string via `",".join(m[:2])`, and
I guess you'd also have to add a comma at the end if you want that, `+","`
Another way to do it would be with regex with capturing. `m =
re.find("^(.*?,.*?,).*", text)` or something like that.
Sorry, my Python is a little rusty.