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
numpy bytes to plain string
提问by V.K.
I have a numpy array X
with dtype 'S' (numpy.bytes_)
. For example printing print(X[0, 0])
yields b'somestring'
. Similarly str(X[0, 0])
returns string "b'somestring'"
.
我有一个numpy的阵列X
有dtype '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 somestring
or 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'