3

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?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
newtopythonXD
  • 39
  • 1
  • 2
  • `re.sub('[0-9]', '', firstname)` and `re.sub('[0-9]', '', lastname)` should do the trick, you have to wrap it inside of `[]` – Cow Apr 01 '22 at 10:49
  • 1
    _it just not working_ isn't helpful at all. What IS the problem? Does the program crash? - provide tracelog. Output not as expected? - post sample input, output, and expected output. See [ask]. – AcK Apr 01 '22 at 11:02
  • I just said, i am new to stackoverflow, nothing happend if i asked first time little bit wrongly. and i asked right because i didnt got any problem no crash and nothing it just didnt worked first without the [] – newtopythonXD Apr 01 '22 at 11:03
  • @newtopythonXD No problem, you can just take a [tour](https://stackoverflow.com/tour). **Friendly reminder**: You forgot to accept the answer. Also, you can delete the answer you posted. – Abhyuday Vaish Apr 01 '22 at 11:09
  • @AbhyudayVaish please stop soliciting the OP to accept your answer (or any answer). They are not obligated to do so – Tomerikoo Apr 01 '22 at 11:35

2 Answers2

2

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
nonDucor
  • 2,057
  • 12
  • 17
0

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
Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27