[英]How do I get xx="$£A" to be a 3 character string
I am using Python 2.7我正在使用 Python 2.7
If I set a variable to xx = '$£A' I get a 4 byte string.如果我将一个变量设置为 xx = '$£A',我会得到一个 4 字节的字符串。 This is because the £ character has a value > 127. In my script, the first line is:
这是因为 £ 字符的值 > 127。在我的脚本中,第一行是:
coding=latin_1编码=latin_1
then further down I have tried: xx = bytearray(B'$£A').decode('latin_1') if I print str(len(xx)), I get the value 4.然后再往下我试过: xx = bytearray(B'$£A').decode('latin_1') 如果我打印 str(len(xx)),我得到值 4。
All I need is as byte array to contain three bytes, ascii value for $, 163=ANSI Latin_1 for £ and ascii value for A.我所需要的只是包含三个字节的字节数组,$ 的 ascii 值,£ 的 163=ANSI Latin_1 和 A 的 ascii 值。
I would appreciate any help.我将不胜感激任何帮助。 Thanks
谢谢
It is dangerous to use characters above 128 unescaped in string constants unless:在字符串常量中使用超过 128 个未转义的字符是危险的,除非:
# coding=xxx
as first or second line in your script# coding=xxx
作为第一行或第二行The recommended way is to escape them:推荐的方法是逃避它们:
xx = b'$\xa3A'
(above would give the correct latin1 string in Python 2 or the correct latin1 encoded bytes in Python 3, whatever the local encoding could be) (以上将在 Python 2 中给出正确的 latin1 字符串或在 Python 3 中给出正确的 latin1 编码字节,无论本地编码是什么)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.