问题
I am trying to replace a character with empty lines using re.sub in python but it is throwing some error
import re
string = "\asdfsdfsdf\dfd\f\df\df\d"
re.sub("\\","",string)
print (string)
Output:
Traceback (most recent call last):
File "variable_concat.py", line 4, in <module>
re.sub("\\","",string)
File "/usr/lib/python2.7/re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/lib/python2.7/re.py", line 244, in _compile
raise error, v # invalid expression
sre_constants.error: bogus escape (end of line)
where is the error
回答1:
You need to define the input string as well as the pattern in raw string notation form.
>>> string = r"\asdfsdfsdf\dfd\f\df\df\d"
>>> print(string)
\asdfsdfsdf\dfd\f\df\df\d
>>> re.sub(r"\\","",string)
'asdfsdfsdfdfdfdfdfd'
If the input string is not defined as raw string, \a
in the string would turn into an unicode character.
来源:https://stackoverflow.com/questions/29482541/regex-sub-is-throwing-some-error-in-python