如何将bytes对象转换为字符串,然后转换为十进制?

2024-10-01 17:34:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将bytes对象转换为Decimal。为了实现它,我首先把它转换成字符串。下面是我把它转换成字符串的函数。在

def strPrepare(self, s):
    return str(s).strip()

然后我将此函数称为:

^{pr2}$

但有了这个代码,我得到的错误是:

Error has occurred: Cannot convert b'6016.0000' to Decimal


Tags: 对象函数字符串代码selfreturnbytesdef
2条回答

为了从^{}对象获得^{},首先需要使用^{}函数对^{}对象进行解码,如下所示:

>>> my_bytes = b'6016.0000'

>>> my_str = my_bytes.decode()
# where `my_str` holds the string value `'6016.0000'`

或者,在将bytes对象类型转换为string时传递^{}参数可能会得到相同的结果:

^{pr2}$

正如Python's ^{} document所说:

if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors)

然后,为了将数字字符串my_str类型转换为^{},只需执行以下操作:

>>> from decimal import Decimal

>>> Decimal(my_str)
Decimal('6016.0000')

在您的代码中,当您使用^{}而不使用encoding参数键入casted bytes对象时,它将返回一个新的字符串,其开头有b'...',如下所示:

>>> str(my_bytes)
"b'6016.0000'"

此行为也在Python's ^{} document中提到:

Passing a bytes object to str() without the encoding or errors arguments falls under the first case of returning the informal string representation (see also the -b command-line option to Python).

{try},而不是strip}。{cd2>一个很好的对象{cd2>可以让这个对象工作。在

相关问题 更多 >

    热门问题