numpy.strings.slice#
- strings.slice(a, start=None, stop=None, step=None, /)[source]#
根据 start、stop、step 指定的切片,对 a 中的字符串进行切片。与常规 Python
slice
对象类似,如果只指定了 start,则将其解释为 stop。- 参数:
- a类数组,具有
StringDType
、bytes_
或str_
数据类型 输入数组
- startNone,整数或整数数组
切片的起始位置,广播到 a 的形状
- stopNone,整数或整数数组
切片的结束位置,广播到 a 的形状
- stepNone,整数或整数数组
切片的步长,广播到 a 的形状
- a类数组,具有
- 返回:
- outndarray
输出数组,数据类型为
StringDType
、bytes_
或str_
,取决于输入类型
示例
>>> import numpy as np >>> a = np.array(['hello', 'world']) >>> np.strings.slice(a, 2) array(['he', 'wo'], dtype='<U5')
>>> np.strings.slice(a, 1, 5, 2) array(['el', 'ol'], dtype='<U5')
可以为不同的数组条目指定不同的起始/结束/步长
>>> np.strings.slice(a, np.array([1, 2]), np.array([4, 5])) array(['ell', 'rld'], dtype='<U5')
负数切片与常规 Python 中的含义相同
>>> b = np.array(['hello world', 'γεια σου κόσμε', '你好世界', '👋 🌍'], ... dtype=np.dtypes.StringDType()) >>> np.strings.slice(b, -2) array(['hello wor', 'γεια σου κόσ', '你好', '👋'], dtype=StringDType())
>>> np.strings.slice(b, [3, -10, 2, -3], [-1, -2, -1, 3]) array(['lo worl', ' σου κόσ', '世', '👋 🌍'], dtype=StringDType())
>>> np.strings.slice(b, None, None, -1) array(['dlrow olleh', 'εμσόκ υοσ αιεγ', '界世好你', '🌍 👋'], dtype=StringDType())