How to remove all characters after a specific character in python?

Solihull picture Solihull · May 24, 2009 · Viewed 275.6k times · Source

I have a string. How do I remove all text after a certain character? (In this case ...)
The text after will ... change so I that's why I want to remove all characters after a certain one.

Answer

Ned Batchelder picture Ned Batchelder · May 25, 2009

Split on your separator at most once, and take the first piece:

sep = '...'
stripped = text.split(sep, 1)[0]

You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.