PyRar
PyRar

Reputation: 549

Eliminate numbers from strings and keep several characters

Trying to eliminate the numbers from some string like this:

'THEO-GREY3JOY' should become 'THEO-GREYJOY'
'JON SNOW4TARGARYEN' should become 'JON SNOW TARGARYEN'

or if they are already strings without numbers just let them be.

I tries this till now but I cuts the spaces and the "-". Not good.

Date_Neprel = pd.read_excel('1st_Incercare.xlsx')
Nume_ColumnPosition = Date_Neprel.columns.get_loc('Nume')
Prenume_ColumnPosition = Date_Neprel.columns.get_loc('Prenume')
for index,row in Date_Neprel.iterrows():
    Date_Neprel.iloc[index,Nume_ColumnPosition] = re.sub(r'[^a-zA-Z ]+', '', row['Nume'])
    Date_Neprel.iloc[index,Prenume_ColumnPosition] = re.sub(r'[^a-zA-Z ]+', '', row['Prenume']) 

Upvotes: 0

Views: 33

Answers (3)

Rajat Jain
Rajat Jain

Reputation: 2022

Try below:

Date_Neprel['Nume'] = Date_Neprel['Nume'].str.replace("[0-9]", "")
Date_Neprel['Prenume'] = Date_Neprel['Prenume'].str.replace("[0-9]", "")

Upvotes: 2

Mahmoud Elshahat
Mahmoud Elshahat

Reputation: 1959

Try this:

import re
text = 'THEO-GREY3JOY JON SNOW4TARGARYEN'

result = re.sub(r'\d+', '', text)

print(result)

output:

THEO-GREYJOY JON SNOWTARGARYEN

Upvotes: 2

mkrana
mkrana

Reputation: 430

i think there could be multiple ways to handle this scenario.

I hope this helps you.

s1 = "THEO-GREY3JOY"
s2 = "JON SNOW4TARGARYEN"

new_string = ''.join([i for i in s1 if not i.isdigit()])
print (new_string)

new_string = ''.join([i for i in s2 if not i.isdigit()])
print (new_string)

Upvotes: 0

Related Questions