2

I cannot work out how to convert a Python string to a numpy unicode string

import numpy as np

py_str = "hello world"
#numpy_str = ?
2
  • What is a numpy unicode string? Are you using Python 2 or 3? Commented Mar 6, 2018 at 9:57
  • 1
    Why not np.array(py_str)? In Py3 that will be uncode. Or np.unicode_(py_str). Generally a single element array is more useful, though they share many of the same attributes and methods. Commented Mar 6, 2018 at 16:46

1 Answer 1

3

To convert a Python string to a numpy string you can simply use the numpy constructor.

>>> import numpy as np
>>> py_str = "hello world"
>>> numpy_str = np.string_(py_str)
>>> type(numpy_str)
<type 'numpy.string_'>

EDIT:

Following @hpaulj suggestion you may find that the dtype of numpy_str is string88 not unicode. Next, I add the code to convert it to unicode with the content, type, and dtype checks.

>>> numpy_str
'hello world'
>>> type(numpy_str)
<type 'numpy.string_'>
>>> numpy_str.dtype.name
'string88'

>>> numpy_unicode = numpy_str.astype(unicode)

>>> numpy_unicode
u'hello world'
>>> type(numpy_unicode)
<type 'numpy.unicode_'>
>>> numpy_unicode.dtype.name
'unicode352'
Sign up to request clarification or add additional context in comments.

1 Comment

@hpaulj Thanks. I updated the answer following your suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.