简体   繁体   中英

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

I am using 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). 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). I should be able to add the numbers, let it equal x, and return 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.

As you are using python 2, use

bytearray("2402") 

or

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

try this if you decide to switch to 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:

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)

that function works in python3, because in py3, for a bytes object b , b[0] will be an int:

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

but as you are using python2, b[0] will be a str:

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

add str and int together is not allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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