[英]Octal string literals and octal command line arguments
我有一个八进制字符串"\\334\\n\\226"
( \\n
不是八进制,因为它具有可打印的ASCII表示)。 我想在一个字节数组中编码,所以我想转换"\\334\\n\\226"
- > [\\334, \\n, \\226]
- > [220, 10, 150]
。 我想写下面的代码:
octal_string = "\334\n\226"
encoded_string = octal_string.encode()
for b in encoded_string:
print(b)
这输出:
195 156 10 194 150
另外,我想将此字符串作为命令行参数传递给我的脚本,所以如果我编写脚本:
import sys
octal_string = sys.argv[1]
encoded_string = octal_string.encode()
for b in encoded_string:
print(b)
然后我跑:
> python3 myscript.py \334\n\226
我明白了:
51 51 52 110 50 50 54
我该怎么做?
您可以将regex或此代码与list comprehension,split()和int()方法一起使用:
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)
引号很重要:
$ python3 myscript.py "\334\n\226"
\334\n\226
['', '334', 'n', '226']
[220, 10, 150]
编辑:在Python3中,此代码有效:
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.