为什么字符串替换功能与' \'不在python中工作?

时间:2018-03-21 18:50:21

标签: python python-3.x

当我把/或\之间放在''似乎替换方法无法捕获斜线。 我尝试使用""而不是它,但又失败了。

h = marshal.dumps(func.__code__).replace(b'\', b'/')

code=h.decode('raw_unicode_escape')

我正在使用python 3.6版本。 功能来自 keras generic_utils.py

def func_dump(func):
    """Serializes a user defined function.`

    # Arguments
        func: the function to serialize.

    # Returns
        A tuple `(code, defaults, closure)`.
    """
    h = marshal.dumps(func.__code__).replace(b str(\), b str(/))
    code=h.decode('raw_unicode_escape')


    defaults = func.__defaults__
    if func.__closure__:
        closure = tuple(c.cell_contents for c in func.__closure__)
    else:
        closure = None
    return code, defaults, closure

1 个答案:

答案 0 :(得分:0)

单个反斜杠'\'interpreted as an escape character。要指定反斜杠字符,您需要使用双反斜杠:

h = marshal.dumps(func.__code__).replace(b'\\', b'/')

或者如果使用Python 3.3+使用原始二进制文字:

h = marshal.dumps(func.__code__).replace(rb'\', b'/')