python用\字符串替换\\

问题描述 投票:1回答:1

我想用Python3将字符串“ foo”转换为[172, 189, 24, 219, 76, 194, 248, 92, 237, 239, 101, 79, 204, 196, 164, 216]。我可以使用Python2做到这一点,但是我无法使用Python3做到这一点。问题描述如下:

我有变量s,它是字符串,其值是:

"\\x17\\x1c"

如何用"\\"替换"\"

s.replace("\\", "\")给我

SyntaxError: EOL while scanning string literal

因此,我假设我必须以某种方式转义\或Python将\视为转义?

编辑:我这样做:

python3:

import hashlib

s = "foo"
s_enc = s.encode("latin1")
m = hashlib.md5(s_enc).digest()
out = str(m)[2:-1] # bytes -> string

现在我不能使用hexdigest(),因为我必须按照python2实现此输出:

import hashlib

s = "foo"
out = hashlib.md5(s).digest()


print(out) # '\xac\xbd\x18\xdbL\xc2\xf8\\\xed\xefeO\xcc\xc4\xa4\xd8'

我必须取得完全相同的字符串,因为我需要遵循一些逻辑,例如:

[ord(i) for i in out]
# [172, 189, 24, 219, 76, 194, 248, 92, 237, 239, 101, 79, 204, 196, 164, 216]

所以,我必须从[172, 189, 24, 219, 76, 194, 248, 92, 237, 239, 101, 79, 204, 196, 164, 216]达到"foo"

python replace backslash
1个回答
-1
投票

使用原始字符串代替s.replace(r"\\", r"\")

© www.soinside.com 2019 - 2024. All rights reserved.