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':['ab_cd_123@email.com', 'ab_cd.12-3@email.com']})
>>> df['EMAIL'].str.replace(r'[._-](?=[^@]*@)', '', regex=True)
0 abcd123@email.com
1 abcd123@email.com
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
break
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
Pandas - Find Rows With Matching Values in Two Columns and Multiply Value in Another Column
How to Continue a Loop After Catching Exception in Try ... Except
Python Pandas .Isnull() Does Not Work on Nat in Object Dtype
Identifying the Range of a Color in Hsv Using Opencv
Passing Multiple Arguments from Django Template Href Link to View
How to Compute the Gradients of Image Using Python
Regex to Find Words Between Two Tags
Opening a Word Document That Has a Password Using Docx Library
Pandas Populate New Dataframe Column Based on Matching Columns in Another Dataframe
How to Use Variables in SQL Statement in Python
How to Select All Elements Greater Than a Given Values in a Dataframe
How to Get One Key and Value from a Json in Python
How to Write List Elements into a Tab-Separated File
How to Ask a Set of Questions Multiple Times Based on User Input