regex sub 在 python 中抛出一些错误 [英] regex sub is throwing some error in python

查看:61
本文介绍了regex sub 在 python 中抛出一些错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 python 中使用 re.sub 用空行替换一个字符,但它抛出了一些错误

导入重新string = "\asdfsdfsdf\dfd\f\df\df\d"re.sub("\\","",string)打印(字符串)

输出:

回溯(最近一次调用最后一次):文件variable_concat.py",第 4 行,在 <module> 中re.sub("\\","",string)文件/usr/lib/python2.7/re.py",第 151 行,在子文件中返回 _compile(pattern, flags).sub(repl, string, count)_compile 中的文件/usr/lib/python2.7/re.py",第 244 行引发错误,v # 无效的表达式sre_constants.error:假转义(行尾)

错误在哪里

解决方案

您需要以原始字符串符号形式定义输入字符串和模式.

<预><代码>>>>字符串 = r"\asdfsdfsdf\dfd\f\df\df\d">>>打印(字符串)\asdfsdfsdf\dfd\f\df\df\d>>>re.sub(r"\\","",string)'asdfsdfsdfdfdfdfdfd'

如果输入的字符串没有定义为原始字符串,字符串中的\a会变成unicode字符.

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

解决方案

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.

这篇关于regex sub 在 python 中抛出一些错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆