Ravi Ravi - 4 years ago 140
Python Question

python regex to replace all single word characters in string

I am trying to remove all the single characters in a string


input: "This is a big car and it has a spacious seats"


my output should be:


output: "This is big car and it has spacious seats"


Here I am using the expression

import re
re.compile('\b(?<=)[a-z](?=)\b')


This matches with first single character in the string ...

Any help would be appreciated ...thanks in Advance

Answer Source

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?

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