简体   繁体   English

如何在Python中将字符串转换为字节,并在字节中添加值?

[英]How to convert string to byte in Python, and add the values in the byte?

I am using Python 2.7.我正在使用 Python 2.7。

I was given the docstring to this function:我得到了这个函数的文档字符串:

def test(a, b):
    ''' takes two bytes, returns the the bytes when the two bytes are added up
    (bytes, bytes) -> bytes
    j = 0
    k = j + b[0]

I tried doing this (which i was told would be a valid input to the function and follows the docstring):我尝试这样做(有人告诉我这将是该函数的有效输入并遵循文档字符串):

test(b"2402", b"testing"):

but this raises an error saying但这引发了一个错误说

TypeError: unsupported operand type(s) for +: 'int' and 'str'

From my understanding, bytes consist of 1's and 0's (ie integers).根据我的理解,字节由 1 和 0(即整数)组成。 So shouldn't I be able to add each index of the byte?那么我不应该能够添加字节的每个索引吗?

Example: test(b"123", b"testing") a and b will be bytes (consisting of 1's and 0's).示例: test(b"123", b"testing") a 和 b 将是字节(由 1 和 0 组成)。 I should be able to add the numbers, let it equal x, and return b"x".我应该能够将数字相加,让它等于 x,然后返回 b"x"。

Edit: The function itself does not need to be solved, I just made it up to use an example to show what I want.编辑:函数本身不需要解决,我只是用一个例子来说明我想要的。 I just want to know how to convert a string to a byte in Python 2.7.我只想知道如何在 Python 2.7 中将字符串转换为字节。

As you are using python 2, use当您使用 python 2 时,请使用

bytearray("2402") 

or或者

"2402".encode('utf-8')

try this if you decide to switch to python 3.x:如果你决定切换到 python 3.x,试试这个:

test(bytes("2402", 'utf-8'), bytes("testing", 'utf-8'))

to covert string to bytes or bytes to string you should provide encoding also if you have bytes, you cannot get correct result with str, but you should use encoding as follows:要将字符串转换为字节或将字节转换为字符串,您还应该提供编码,如果您有字节,则无法使用 str 获得正确的结果,但您应该使用如下编码:

b"abcde".decode("utf-8") 

You should consider another thing that indexing on bytes will not return a byte, instead is returning integer try this:您应该考虑另一件事,即对字节进行索引不会返回一个字节,而是返回整数,试试这个:

>>>type(b[0])
<class 'int'>

because bytes and bytearray objects are sequences of integers (between 0 and 255)因为 bytes 和 bytearray 对象是整数序列(0 到 255 之间)

that function works in python3, because in py3, for a bytes object b , b[0] will be an int:该函数在 python3 中有效,因为在 py3 中,对于字节对象bb[0]将是一个整数:

>>> type(b'abc'[0])
<class 'int'>

but as you are using python2, b[0] will be a str:但是当您使用 python2 时, b[0]将是一个 str:

>>> type(b'abc'[0])
<type 'str'>

add str and int together is not allowed.不允许将 str 和 int 添加在一起。

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

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