Eric Choi Eric Choi - 1 year ago 108
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download