Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Octal string literals and octal command line arguments

I have an octal string "\334\n\226" (the \n is not in octal because it has a printable ASCII representation). I would like to encode this in a bytes array, so I would like to convert "\334\n\226" -> [\334, \n, \226] -> [220, 10, 150]. I thought to write the following code:

octal_string = "\334\n\226"
encoded_string = octal_string.encode()
for b in encoded_string:
  print(b)

This outputs:

195 156 10 194 150

Additionally I would like to pass this string as a command line argument to my script so if I write the script:

import sys

octal_string = sys.argv[1]
encoded_string = octal_string.encode()
for b in encoded_string:
  print(b)

Then I run:

> python3 myscript.py \334\n\226

I get:

51 51 52 110 50 50 54

How am I supposed to do this?

like image 788
Benjy Kessler Avatar asked Nov 18 '25 06:11

Benjy Kessler


1 Answers

You can use regex or this code with list comprehension, split() and the int() method:

import sys

if len(sys.argv) == 2:

    s=sys.argv[1]
    print(s)
    print(s.split("\\"))
    rslt=[ 10 if e=="n" else int(e,8) for e in s.split("\\") if e ]
    print(rslt)

The quotation marks are important:

$ python3 myscript.py "\334\n\226"
\334\n\226
['', '334', 'n', '226']
[220, 10, 150]

EDIT: In Python3 this code works:

b= bytes(sys.argv[1],"utf8")
print(b)
#rslt= [ ord(c) for c in str(b,"unicode-escape") ]
rslt= [ ord(c) for c in b.decode("unicode-escape") ]
print(rslt) 

b'\\334\\ne\\226'
[220, 10, 101, 150]

EDIT2:

import ast

s= ast.literal_eval("'"+sys.argv[1]+"'")  # It interprets the escape sequences,too.
print( [ord(c) for c in s ] )

[220, 10, 101, 150]
like image 96
kantal Avatar answered Nov 19 '25 19:11

kantal