Search code examples
pythonstringsplit

Dividing a string at various punctuation marks using split()


I'm trying to divide a string into words, removing spaces and punctuation marks.

I tried using the split() method, passing all the punctuation at once, but my results were incorrect:

>>> test='hello,how are you?I am fine,thank you. And you?'
>>> test.split(' ,.?')
['hello,how are you?I am fine,thank you. And you?']

I actually know how to do this with regexes already, but I'd like to figure out how to do it using split().


Solution

  • This is the best way I can think of without using the re module:

    "".join((char if char.isalpha() else " ") for char in test).split()