python regex to replace all single word characters in string

Edit: I have just seen that this was suggested in the comments first by Wiktor Stribiżew. Credit to him - I had not seen when this was posted.

You can also use re.sub() to automatically remove single characters (assuming you only want to remove alphabetical characters). The following will replace any occurrences of a single alphabetical character:

import re
input =  "This is a big car and it has a spacious seats"

output =  re.sub(r"\b[a-zA-Z]\b", "", input)

>>>
output = "This is  big car and it has  spacious seats"

You can learn more about inputting regex expression when replacing strings here: How to input a regex in string.replace?


Here's one way to do it by splitting the string and filtering out single length letters using len and str.isalpha:

>>> s = "1 . This is a big car and it has a spacious seats"
>>> ' '.join(i for i in s.split() if not (i.isalpha() and len(i)==1))
'1 . This is big car and it has spacious seats'