Home > Mobile >  Python sum string (?)
Python sum string (?)

Time:06-22

I receive from a server this answer a =b'[10,20]'

  1. How to sum values?
  2. If I use sum(a) I get 423. Why?

CodePudding user response:

b'[10,20]' is a bytes object. Unlike an str (unicode in Python 2), it expands into a list of integers 0..255:

>>> list(b'[10,20]')
[91, 49, 48, 44, 50, 48, 93]

Perhaps what you want to do is to parst the json and then get a sum of the resulting list:

>>> import json
>>> sum(json.loads(b'[10,20]'))
30

CodePudding user response:

A bytes value is a sequence of integers; for display purposes, ASCII characters are used where possible.

>>> list(b'[10,20]')
[91, 49, 48, 44, 50, 48, 93]
>>> sum(_)
423

You want to decode the bytes value to a str, then parse that as a list of int values.

>>> import ast
>>> sum(ast.literal_eval(b'[10,20]'.decode()))
30

CodePudding user response:

To sum the list a you can use the json package for python and just convert to a list.

There are some simple ways to accomplish that:

>>> import json
>>> json.loads(a)
[10,20]
>>> sum(json.loads(a))
30

The sum results in 423 because a it's a bytes object, a sequence of ints that gives an ascii-rapresentation when displayed using repr() or str()

take a look at this:

>>> a = b'[1,2,3]'
>>> list(a)
[91, 49, 44, 50, 44, 51, 93]

As you can see it's a sequence of integers and not a sequence of characters, like a string.

  • Related