Eric Choi Eric Choi - 5 months ago 27
Python Question

how to take away all the spaces and punctuation in a string? (python)

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.



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.