Skip to content

How to remove characters after 2 certain characters in a Python string?

An answer to this question on Stack Overflow.

Question

Lets say I have a bunch of strings, and they can only be in the following formats:

format1 = 'substring1#substring2'
format2 = 'substring1$substring2'
format3 = 'substring1'

Let me explain. The strings are sometimes divided using the # or $ character. However other times, they are not.

I want to remove the part that appears after the # or $, if it exists. If it was just one special character, that is #, I could have done this:

string = string.split('#')[0]

But how can I do it for the 2 special characters in a quick and elegant way? Also assume the following things:

  1. Only one special character can appear in the string.
  2. The special characters will not appear in any other part of the string.

Thanks.

Answer

Regular expressions.

import re
re.sub('[$#].*', '', string_to_modify)