0

how can be remove special characters from the string?

19th Jan 2020, 12:21 PM
SUDHANSHU TIWARI
SUDHANSHU TIWARI - avatar
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
19th Jan 2020, 2:16 PM
Jianmin Chen
Jianmin Chen - avatar
+ 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?
19th Jan 2020, 12:38 PM
HonFu
HonFu - avatar
+ 2
Or you write: new_string = ''.join(letter for letter in old_string if letter.isalnum() or letter.isspace())
19th Jan 2020, 3:35 PM
HonFu
HonFu - avatar
+ 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)
19th Jan 2020, 1:19 PM
Thống Nguyễn
Thống Nguyễn - avatar