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

Viewed 135

I have a variable x which has value '\202', I want to convert x into raw_x = '\\202'. I have tried couple of things below, but didn't get desired output.

x = '\202'     #we cannot modify x = r'\202', 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'\202' or raw_x = '\\202'
print("Desired raw_x output: \\202")

Console Output:

'\x82'
\x82
Desired raw_x output: `\202`
1 Answers

As stated in document:

\ooo --> Character with octal value ooo

So it's a character, all you have to do is get it's Unicode code point number(in base 10) with .ord() then convert that number to octal with .oct() which gives octal string prefixed with “0o”: (or just simply do interested_part = f'{ord(x):o}')

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

output :

\202
\\202

explanation:

x = '\202'
x = ord(x)
print(x)     # 130

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

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