def pre_process(t):
""" (str) -> str
returns a copy of the string with all punctuation removed, and all letters set to lowercase. The only characters in the output will be lowercase letters, numbers, and whitespace.
"""
Asked
Active
Viewed 3,308 times
-1
-
What you tried? Did you googled? If you would have, you would have got the answer as first link – Moinuddin Quadri Oct 19 '16 at 23:11
-
Check the [Google Search](https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=python%20remove%20all%20spaces%20and%20punctuation%20from%20the%20string) result – Moinuddin Quadri Oct 19 '16 at 23:13
-
Have you tried my answer? – Oct 20 '16 at 01:24
3 Answers
1
Try the following code.
import re
string = 'This is an example sentence.'
string = re.sub(r'[^a-zA-Z\d]', string)
print(string)
You should get out Thisisanexamplesentance
.

Zak
- 1,910
- 3
- 16
- 31
-
-
Well observed! I've put numbers in there as well, I assume that's what the OP wants. – Zak Oct 19 '16 at 23:31
0
Just rebuild your string with only alpha-numeric characters:
''.join(_char for _char in _str.lower() if _char.isalnum())

midori
- 4,807
- 5
- 34
- 62
0
This is the simplest function using regex
I could put together to achieve your requirement.
import re
def pre_process(t):
return re.sub(r'[^a-z\d ]','',str.lower())
It will return the input string in lower case, and omit any characters that are not letters, numbers or whitespace.

maze88
- 850
- 2
- 9
- 15