How to decode a numpy array of dtype=numpy.string_?
<p>I need to decode, with Python 3, a string that was encoded the following way:</p>

<pre><code>&gt;&gt;&gt; s = numpy.asarray(numpy.string_("hello\nworld"))
&gt;&gt;&gt; s
array(b'hello\nworld', 
      dtype='|S11')
</code></pre>

<p>I tried:</p>

<pre><code>&gt;&gt;&gt; str(s)
"b'hello\\nworld'"

&gt;&gt;&gt; s.decode()
AttributeError                            Traceback (most recent call last)
&lt;ipython-input-31-7f8dd6e0676b&gt; in &lt;module&gt;()
----&gt; 1 s.decode()

AttributeError: 'numpy.ndarray' object has no attribute 'decode'

&gt;&gt;&gt; s[0].decode()
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
&lt;ipython-input-34-fae1dad6938f&gt; in &lt;module&gt;()
----&gt; 1 s[0].decode()

IndexError: 0-d arrays can't be indexed
</code></pre>

<p>In Python 3, there are two types that represent sequences of characters:    <code>bytes</code> and <code>str</code> (contain Unicode characters). When you use <code>string_</code> as your type, numpy will return <code>bytes</code>. If you want the regular <code>str</code> you should use <code>unicode_</code> type in numpy:</p>

<pre><code>&gt;&gt;&gt; s = numpy.asarray(numpy.unicode_("hello\nworld"))
&gt;&gt;&gt; s
array('hello\nworld', 
      dtype='&lt;U11')

&gt;&gt;&gt; str(s)
'hello\nworld'
</code></pre>

<p>But note that if you don't specify a type for your string (string_ or unicode_) it will return the default str type (which in python 3.x is the str (contain the unicode characters)).</p>

<pre><code>&gt;&gt;&gt; s = numpy.asarray("hello\nworld")
&gt;&gt;&gt; str(s)
'hello\nworld'
</code></pre>

python string python-3.x numpy