0
how can be remove special characters from the string?
4 ответов
+ 3
This is actually very simple, so I'll answer. If you're using regular expressions, you can do this:
import re
string = input("")
special_char = re.compile(r"[\W\S]") #anything not a letter, underscore, or space
Now, you can use re.sub:
re.sub(special_char, "", string) #applies regex to string and removes special characters
If you can't use regex, do this:
white_list = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz") #converts this to a set
string = "".join(filter(white_list.__contains__, string)) #removes anything not in the set white_list
+ 3
You can create a new string using some sort of loop, where you only add the letters from the original string that you want.
Use 'if' for that.
Give it a try and show us?
+ 2
Or you write:
new_string = ''.join(letter for letter in old_string if letter.isalnum() or letter.isspace())
+ 1
Try this bro:
import re
usinput = input('Please type in your string: \n')
result = re.sub(r"[^a-zA-Z0-9\s]","", usinput)
print(result)