Joseph Nicolls
Joseph Nicolls

Reputation: 33

How to remove a specific space using regular expressions.

I have the following bit of code:

import re

s = 'The quic k brown fox jumps over the lazy dog.'
pattern = re.compile(r'(\sk\s)')
s = re.sub(pattern, 'k ', s)

I want 's' to have a final result of "The quick brown fox jumped over the lazy dog. However, the final string result remains unchanged.

What should I change?

Upvotes: 1

Views: 91

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626861

When you compile a regex object, you are most likely to use it instead of "static" re methods.

Thus, in your case, you will use sub of the compiled regex object:

s = 'The quic k brown fox jumps over the lazy dog.'
pattern = re.compile(r'\sk\s')
s = pattern.sub('k ', s)
print s

See demo

Output: The quick brown fox jumps over the lazy dog.

Else, just replace your pattern declaration to

pattern = r'\sk\s'

Note the parentheses are redundant here, you are not using the captured group text.

Also, if there are any hard spaces in the input string, you might want to replace them with normal spaces first with

s = s.replace(u'\xa0', u' ')

Another sample code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

s = u'The quic k brown fox jumps over the lazy dog.'
s = s.replace(u'\xa0', u' ')
pattern = re.compile(ur'\sk\s')
s = pattern.sub(u'k ', s)
print s

Upvotes: 1

Related Questions