简体   繁体   English

在Python中形成字节串

[英]Forming a byte string in Python

I am creating a method in Python whereby it will take a number which will form a byte string that will then get sent to the Arduino. 我正在Python中创建一个方法,该方法将采用一个数字,该数字将形成一个字节字符串,然后将其发送到Arduino。 However whenever I try, the escape character is always included in the final byte string. 但是,无论何时尝试,转义字符总是包含在最后的字节字符串中。

Here is the snippet of the code I am using: 这是我正在使用的代码的片段:

num = 5
my_str = '\\x4' + str(num)
my_str.encode('utf-8')

Result: 结果:

b'\\x45'

I tried another method: 我尝试了另一种方法:

num2 = 5
byte1 = b'\\x4'
byte2 = bytes(str(num2), 'ISO-8859-1')
new_byte = byte1 + byte2
new_byte

Result: 结果:

b'\\x45'

Trying yet in a different way: 以另一种方式尝试:

num = 5
u = chr(92) + 'x4' + str(num)
u.encode('ISO-8859-1')

Result: 结果:

b'\\x45'

I would like to get the byte string to be b'\\x45' without the escape character but not really sure what I have missed. 我想将字节字符串设置为b'\\ x45',但不使用转义字符,但不能确定我错过了什么。 I will appreciate any pointers on how I can achieve this. 我将不胜感激如何实现这一目标。

Your problem is that you have already escaped the backslash. 您的问题是您已经逃脱了反斜杠。 It is not recommended to construct a literal using an unknown variable, especially if there's a simpler way, which there is: 不建议使用未知变量来构造文字,特别是如果有一种更简单的方法,那就是:

def make_into_bytes(n):
    return bytes([64 + n])

print(make_into_bytes(5))

This outputs 这个输出

b'E'

Note that this isn't a bug, as this is simply the value of 0x45: 请注意,这不是错误,因为它只是0x45的值:

>>> b'\x45'
b'E'

The way this function works is basically just doing it by hand. 此功能的工作方式基本上只是手工完成。 Prepending '4' to a hex string (of length 1) is the same as adding 4 * 16 to it, which is 64. I then construct a bytes object out of this. 在十六进制字符串(长度为1)前加“ 4”与向其添加4 * 16(即64)相同。然后,​​我从中构造一个字节对象。 Note that I assume n is an integer, as in your code. 请注意,我假设n是一个整数,如您的代码所示。 If n should be a digit like 'a' , this would be the integer 10 . 如果n应该是像'a'这样的数字,则它将是整数10

If you want it to work on hex digits, rather than on integer digits, you would need to change it to this: 如果希望它以十六进制数字而不是整数数字工作,则需要将其更改为:

def make_into_bytes(n):
    return bytes([64 + int(n, 16)])

print(make_into_bytes('5'))
print(make_into_bytes('a'))

with output 带输出

b'E'
b'J'

This quite simply converts the digit from base 16 first. 这很简单地首先转换了以16为底的数字。

You can use the built-in function chr() to convert an integer to the corresponding character: 您可以使用内置函数chr()将整数转换为相应的字符:

>>> chr(0x40 + 5)
'E'

Alternatively, if you just one to get the n-th letter of the alphabet, it might be more readable to use str.ascii_uppercase 另外,如果仅用一个来获取字母表的第n个字母,则使用str.ascii_uppercase可能更易读。

>>> string.ascii_uppercase[5 - 1]
'E'

Note that the results in this answer are strings in Python 3, not bytes objects. 请注意,此答案的结果是Python 3中的字符串,而不是bytes对象。 Simply calling .encode() on them will convert them to bytes . 只需对它们调用.encode()即可将其转换为bytes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM