如何在Python中将字节转换为str?

时间:2019-08-21 21:12:50

标签: python-3.x byte amazon-kinesis

我正在从运动学流中读取此记录,然后看到此问题:

event: {'Records': [{'kinesis': {'kinesisSchemaVersion': '1.0', 'partitionKey': '1', 'sequenceNumber': '49598713911021236248095996540994479657456990259863617538', 'data': 'SGVsbG8sIHRoaXMgaXMgYSB0ZXN0Lg==', 'approximateArrivalTimestamp': 1566421493.064}, 'eventSource': 'aws:kinesis', 'eventVersion': '1.0',

[ERROR] TypeError: can only concatenate str (not "bytes") to str Traceback (most recent call last):   File "/var/task/handler.py", line 11, in extract     print("raw = " + raw)

这是我的代码:

print("context: ", context)
print("event: ", event)

for record in event['Records']:
    raw = base64.b64decode(record['kinesis']['data'])
    print("raw = " + raw)

为什么它在raw = " + raw失败?不是字符串吗?

1 个答案:

答案 0 :(得分:0)

b64decode返回bytes,因此在进行串联之前,您需要将其解码为str

例如:

print("context: ", context)
print("event: ", event)

for record in event['Records']:
    raw = base64.b64decode(record['kinesis']['data']).decode('utf-8')
    print("raw = " + raw)