Home > Enterprise >  Fix KeyError: '\\s' when trying to replace a substring with one that includes special ch
Fix KeyError: '\\s' when trying to replace a substring with one that includes special ch

Time:09-13

import re

input_text = "Hello!, How are you? "

#input_text = re.sub(" ", r"[\s|-|]", input_text)
input_text, nro_repl = re.subn(' ', r'[\s|-|]', input_text)

print(repr(input_text))
print(repr(nro_repl))

The correct output:

4
'Hello!,[\s|-|]How[\s|-|]are[\s|-|]you?[\s|-|]'

The error that I get:

Traceback (most recent call last):
    this = chr(ESCAPES[this][1])
KeyError: '\\s'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
    raise s.error('bad escape %s' % this, len(this))
re.error: bad escape \s at position 1

How do I fix this error and get the desired result, managing to have the input string but making the replacements by substrings with the special characters?

CodePudding user response:

In the manual that @Nick posted it tells us that there will be no backslash escape processing of the replacement if we pass a function instead of a string. So all you have to do is replace the string argument with a lambda returning the string.

import re

input_text = "Hello!, How are you? "
input_text, nro_repl = re.subn(' ', lambda x: '[\s|-|]', input_text)

print(repr(nro_repl))
print(repr(input_text))

output:

4
'Hello!,[\\s|-|]How[\\s|-|]are[\\s|-|]you?[\\s|-|]'
  • Related