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>Another option is the <code>np.char</code> collection of string operations.</p>

<pre><code>In [255]: np.char.decode(s)
Out[255]: 
array('hello\nworld', 
      dtype='&lt;U11')
</code></pre>

<p>It accepts the <code>encoding</code> keyword if needed.  But <code>.astype</code> is probably better if you don't need this.</p>

<p>This <code>s</code> is 0d (shape ()), so needs to be indexed with <code>s[()]</code>.</p>

<pre><code>In [268]: s[()]
Out[268]: b'hello\nworld'
In [269]: s[()].decode()
Out[269]: 'hello\nworld'
</code></pre>

<p><code>s.item()</code> also works.</p>

python string python-3.x numpy