Just for learning I am trying to replace all the special characters present in the keyboard to replace with underscore'_'
List of characters= ~!@#$%^&*()+|}{:"?><-=[]\;',./
string I created:
table = """123~!@#$%^&*()+|}{:"?><-=[]\;',./"""
import re
table1= re.sub(r'!~@#$%^&*()-+={}[]:;<.>?/\'"', '_', table)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/lib64/python2.7/re.py", line 242, in _compile
raise error, v # invalid expression
sre_constants.error: unexpected end of regular expression
Unable to do so I am getting the above error.
How can I replace the special characters in the string using regex
table = """..."""Also, what's with the123at the beginning?)-+creates an invalid range. Always put the-at the end/start of the character class. Yeah, and use a character class :)123\W, which matches-all non-word characters:re.sub(r'\W', '_', some_string). docs.python.org/3/library/re.html#regular-expression-syntax[^\w\s]though, depending on what exactly OP wants to replace. Also, there seem to be chars like|what shall not be replaced (might be a mistake in the question, though).