Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 806
Ravi Avatar asked Feb 06 '17 11:02

Ravi


People also ask

How do you replace all occurrences of a regex pattern in a string in Python?

sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.

How do I replace a word in a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

How do you replace a word in a string in Python?

Python String replace() MethodThe replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.


1 Answers

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?

like image 157
Chuck Avatar answered Oct 16 '22 17:10

Chuck