如何在python中打印原始编码字符串进行串口编程?

时间:2014-09-28 03:10:18

标签: python string serial-port

我的问题很简单,我有一个类似" \ x55"

的字符串

如果我这样做

print "\x55"

Python将打印为

U

我想要的是打印" \ x55" .xxxx,结果应该是原始格式" \ x55",我该怎么做?

更具体地说,

>>> a = '"\x01\x01\x02\x00\x00\x00&'
>>> a
'"\x01\x01\x02\x00\x00\x00&'
>>> print a
"&

但我想要的是什么时候

>>> print somebuild-infunction(a) #maybe a.noencoding()

返回

\x22\x01\x01\x02\x00\x00\x00\x26

更新

我不知道为什么我会投票,但我仍然希望分享以下我刚写的内容。 我在串口设备类中需要这些工具功能,所以我可以简单地使用serial.write()将命令发送到我的设备。

And I found a bug in python, that is even you commented out '\x', the interpreter still considers it as a ValueError: wrong escape of '\x', so I added '\' in the comments.

def hex2str(src, zeropad = 2):
    """
    convert hex number 0x55 to '0x55', 0x1 to '0x01', with zero pad.
    """
    return '0x' + hex(src)[2:].zfill(zeropad)

def hex2bytestring(src):
    """
    convert 0x55 to \\x55
    """
    return chr(int(hex(src),16))

def bytestring2hex(src):
    """
    convert \\x55 into int (not '0x55' but 85)
    """
    return int(src.encode('hex'),16)

def list2bytestr(src):
    """
    convert [0x55, 0x01 ...] to "\\x55\\x01..."
    """
    return ''.join([hex2bytestring(x) for x in src])

def bytestr2list(src):
    """
    reverse of list2bytestr
    """
    return [int(ch.encode('hex'),16) for ch in src]

def dispbytestr(src):
    """
    src is byte string like '\\x55\\x01'
    print byte string as the original encoded format.
    But this output is not actually the byte string, instead, it is the raw string.

    Alternative:
    print ''.join(r'\\x' + ch.encode('hex') for ch in src)
    """
    print ''.join(r'\x%02X' % ord(ch) for ch in src )

3 个答案:

答案 0 :(得分:0)

尝试添加额外的斜杠:

print "\\x55"

如果您无法编辑字符串,请尝试以下操作:

print hex(ord("\x55"))
# "0x55"
# This will still be stored a a hexadecimal answer
# Put str() around it to make it a string

或者基于之前答案的更长版本:

print "".join(["\\x",str(hex(ord("\x55")))[2::]])
# "\x55"
# This will be stored a a string on the other hand

或者如果您正在使用输入线,请尝试:

def hex_to_string(lst):
    temp = []
    for v in lst:
        s = str(hex(ord(v)))
        temp.append("".join(["\\x","0"*(4-len(s)),s[2::]]))
    return "".join(temp)

答案 1 :(得分:0)

您可以将字符串保留为原始字符串:

>>> t = r"\x55"
>>> print t
\x55

答案 2 :(得分:0)

您可以将字符串格式化为具有您想要的字符。

>>> a = '"\x01\x01\x02\x00\x00\x00&'
>>> print ''.join(r'\x%02X'%ord(ch) for ch in a)
\x22\x01\x01\x02\x00\x00\x00\x26
>>> 

%02X将整数值格式化为两位十六进制表示。

ord(ch)将单字符字符串转换为整数值。

for ch in a将字符串a分隔为各个字符。

''.join(...)将一组字符串连接成一个字符串。