Eric Choi Eric Choi - 1 month ago 6
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.

"""

Answer

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.

Comments