0

How do we remove or replace some other special characters like alphabets and punctuations from a string in Python? I have thought to check for the special characters using string.ascii_letters and string.punctuation but, it haven't worked for me. I want only numbers from 0 to 9 to be taken, rather if user enter a special character then it needs to replaced with empty (Like this--> ''). So, is there any way to replace them?

Here is my Python code:

import string

mobile_no = '12aA%!@h34567890'
alpha_characters = list(string.ascii_letters)
special_characters = list(string.punctuation)

if alpha_characters in mobile or special_characters in mobile:
    corrected = mobile_no.replace(alpha_characters, '')
    corrected = mobile_no.replace(special_characters, '')
    print(corrected)

Please correct me, if I'm wrong

1 Answers1

2

You need to loop:

other_characters = string.ascii_letters + string.punctuation
corrected = mobile_no[:]
for char in other_characters:
    corrected = corrected.replace(char, '')
print(corrected)

I would do:

other_characters = string.ascii_letters + string.punctuation
corrected = ''.join([i for i in mobile_no if i not in other_characters])

Or as @matle mentioned:

corrected = "".join([f for f in mobile_no if f in "1234567890"])
U13-Forward
  • 69,221
  • 14
  • 89
  • 114