Python numpy 字节到纯字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23618218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:14:25  来源:igfitidea点击:

numpy bytes to plain string

pythonnumpy

提问by V.K.

I have a numpy array Xwith dtype 'S' (numpy.bytes_). For example printing print(X[0, 0])yields b'somestring'. Similarly str(X[0, 0])returns string "b'somestring'".

我有一个numpy的阵列Xdtype 'S' (numpy.bytes_)。例如印刷print(X[0, 0])产量b'somestring'。同样str(X[0, 0])返回 string "b'somestring'"

However I need to print or convert to string so that it does not contain b'at the beginning and 'at the end. I just want to print somestringor return a string "somestring". How to do it?

但是我需要打印或转换为字符串,以便它b'在开头和'结尾不包含。我只想打印somestring或返回一个 string "somestring"。怎么做?

Note: I cannot change the type of the array.

注意:我无法更改数组的类型。

采纳答案by Alex Thornton

You just need to decode the string back into ASCII, so it would just be:

你只需要将字符串解码回 ASCII,所以它只是:

bytes_string.decode('UTF-8')


Demo:

演示:

>>> b'somestring'.decode('UTF-8')
'somestring'