Python <type 'numpy.string_'> 和 <type 'str'> 类型有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30086936/
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 07:56:21  来源:igfitidea点击:

What is the difference between the types <type 'numpy.string_'> and <type 'str'>?

pythonstringnumpytypes

提问by Blunt

Is there a difference between the types <type 'numpy.string_'>and <type 'str'>?

类型<type 'numpy.string_'>和之间有区别<type 'str'>吗?

采纳答案by Alex Riley

numpy.string_is the NumPy datatype used for arrays containing fixed-width byte strings. On the other hand, stris a native Python type and can not be used as a datatype for NumPy arrays*.

numpy.string_是用于包含固定宽度字节字符串的数组的 NumPy 数据类型。另一方面,str是本机 Python 类型,不能用作 NumPy 数组*的数据类型。

If you create a NumPy array containing strings, the array will use the numpy.string_type (or the numpy.unicode_type in Python 3). More precisely, the array will use a sub-datatype of np.string_:

如果您创建一个包含字符串的 NumPy 数组,该数组将使用该numpy.string_类型(或numpy.unicode_Python 3 中的类型)。更准确地说,该数组将使用以下子数据类型np.string_

>>> a = np.array(['abc', 'xy'])
>>> a
array(['abc', 'xy'], dtype='<S3')
>>> np.issubdtype('<S3', np.string_)
True

In this case the datatype is '<S3': the <denotes the byte-order (little-endian), Sdenotes the string type and 3indicates that each value in the array holds up to three characters (or bytes).

在这种情况下,数据类型是'<S3':the<表示字节顺序(little-endian),S表示字符串类型并3表示数组中的每个值最多包含三个字符(或字节)。

One property that np.string_and strshare is immutability. Trying to increase the length of a Python strobject will create a new object in memory. Similarly, if you want fixed-width NumPy array to hold more characters, a new larger array will have to be created in memory.

np.string_str共享的一个属性是不变性。尝试增加 Pythonstr对象的长度将在内存中创建一个新对象。同样,如果您希望固定宽度的 NumPy 数组容纳更多字符,则必须在内存中创建一个新的更大的数组。



* Note that it is possible to create a NumPy objectarray which contains referencesto Python strobjects, but such arrays behave quite differently to normal arrays.

* 请注意,可以创建一个object包含对 Python对象的引用的 NumPy数组str,但此类数组的行为与普通数组完全不同。