如何将字符串变量值 x='\202' 转换为 python 中的原始字符串值 x='\\202" 3

How to convert string variable value x='\202' into raw string value x='\\202" in python 3

我有一个变量 x,其值为 '2',我想将 x 转换为 raw_x = '\202'。我已经尝试了下面的几件事,但没有得到想要的输出。

x = '2'     #we cannot modify x = r'2', because x is coming from other source
print(x)

raw_x = fr"{x}"
print(raw_x)

raw_x = r"{}".format(x)
print(raw_x)

raw_x = "%r" %x
print(raw_x)

raw_x = x.encode("unicode_escape").decode()
print(raw_x)
# Desire raw_x = r'2' or raw_x = '\202'
print("Desired raw_x output: \202")

控制台输出:

'\x82'
\x82
Desired raw_x output: `2`

document所述:

\ooo --> Character with octal value ooo

所以它是一个字符,你所要做的就是用 .ord() then convert that number to octal with .oct() 得到它的 Unicode 代码点编号(以 10 为基数),它给出以“0o”为前缀的八进制字符串:(或者只是简单地做 interested_part = f'{ord(x):o}')

x = '2'
interested_part = oct(ord(x))[2:]
print('\' + interested_part)
print(r'\' + interested_part)

输出:

2
\202

说明:

x = '2'
x = ord(x)
print(x)     # 130

x = oct(x)
print(x)     # 0o202

print(x[2:]) # removing the octal notation