How to remove numbers from strings?

Viewed 335

I had a mission to just print in reverse the firstname and lastname that the user is inputting. working fine but I tried through import re, and re.sub to just delete any numbers if the user mistakely inputting numbers inside and it just not working.

Here is the code:

import re

firstname = input("enter first name:")
lastname = input("enter last name:")
firstname = re.sub('1-9', '', firstname)
lastname = re.sub('1-9', '', lastname)
print(lastname, firstname)

What is the problem in here?

2 Answers

The pattern '1-9' will match the string 1-9. If you want to specify a set of characters, you should enclose it with []:

print(re.sub('[1-9]', '', 'Name 1with 12numbers'))
# >> Name with numbers

You can either use \d+ to remove digits:

import re
firstname = input("enter first name:")
lastname = input("enter last name:")
firstname = re.sub('\d+', '', firstname)
lastname = re.sub('\d+', '', lastname)
print(lastname, firstname)

Or use [0-9]:

import re
firstname = input("enter first name:")
lastname = input("enter last name:")
firstname = re.sub('[0-9]', '', firstname)
lastname = re.sub('[0-9]', '', lastname)
print(lastname, firstname)

Output:

enter first name:Hello12
enter last name:World23
World Hello
Related