regex sub is throwing some error in python

雨燕双飞 提交于 2019-12-12 06:21:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!