How to Remove All Characters Before a Specific Character in Python

How to remove all characters before a specific character in Python?

Use re.sub. Just match all the chars upto I then replace the matched chars with I.

re.sub(r'^.*?I', 'I', stri)

Pandas: Remove all characters before a specific character in a dataframe column

Using str.replace:

df["address"] = df["address"].str.replace(r'^[^,]*,\s*', '')

Here is a regex demo showing that the logic is working.

How to remove special characters from a string before specific character?

You can use

df['NEW_EMAIL'] = df['EMAIL'].str.replace(r'[._-](?=[^@]*@)', '', regex=True)

See the regex demo. Details:

  • [._-] - a ., _ or - char
  • (?=[^@]*@) - a positive lookahead that requires the presence of any zero or more chars other than @ and then a @ char immediately to the right of the current location.

If you need to replace/remove any special char, you should use

df['NEW_EMAIL'] = df['EMAIL'].str.replace(r'[\W_](?=[^@]*@)', '', regex=True)

See a Pandas test:

>>> import pandas as pd
>>> df = pd.DataFrame({'EMAIL':['', '']})
>>> df['EMAIL'].str.replace(r'[._-](?=[^@]*@)', '', regex=True)
Name: EMAIL, dtype: object

Python: delete all characters before the first letter in a string

Instead of just removing white spaces, for removing any char before first letter, do this :

#s is your string
for i,x in enumerate(s):
if x.isalpha() #True if its a letter
pos = i #first letter position

new_str = s[pos:]

Strip part of string before a particular character, in a case where the character occurs multiple times

split isn't the best approach for this. You want to use a regular expression.

import re

def process_str(in_str):
return re.sub('^.*?: ', '', in_str)

This returns the string without anything up to the first : (colon followed by space). You can read more about Python regular expressions here.

Related Topics

Leave a reply