【问题标题】:regex sub is throwing some error in python正则表达式子在 python 中抛出一些错误
【发布时间】:2015-04-07 02:05:17
【问题描述】:

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

import re

string = "\asdfsdfsdf\dfd\f\df\df\d"
re.sub("\\","",string)
print (string)

输出:

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)

哪里出错了

【问题讨论】:

    标签: python regex replace str-replace


    【解决方案1】:

    您需要定义输入字符串以及原始字符串表示法形式的模式。

    >>> string = r"\asdfsdfsdf\dfd\f\df\df\d"
    >>> print(string)
    \asdfsdfsdf\dfd\f\df\df\d
    >>> re.sub(r"\\","",string)
    'asdfsdfsdfdfdfdfdfd'
    

    如果输入字符串未定义为原始字符串,则字符串中的\a 将转换为 unicode 字符。

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多