NumPy 提供了许多字符串处理函数,它们被定义在用于处理字符串数组的 numpy.char 这个类中,这些函数的操作对象是 string 或者 unicode 字符串数组。
下面是最常用的8个字符串处理函数:
import numpy as np
str1 = np.array(['hello', 'world'])
str2 = np.array([' ', 'numpy'])
result = np.char.add(str1, str2)
print(result)
# 输出:['hello numpy' 'world numpy']
np.char.multiply():将字符串重复多次
import numpy as np
str1 = np.array(['abc', 'def'])
result = np.char.multiply(str1, 3)
print(result)
# 输出:['abcabcabc' 'defdefdef']
import numpy as np
str1 = np.array(['hello', 'world'])
result = np.char.center(str1, 20, '-')
print(result)
# 输出:['-------hello--------' '-------world--------']
import numpy as np
str1 = np.array(['hello', 'world'])
result = np.char.capitalize(str1)
print(result)
# 输出:['Hello' 'World']
import numpy as np
str1 = np.array(['HELLO', 'World'])
result = np.char.lower(str1)
print(result)
# 输出:['hello' 'world']
import numpy as np
str1 = np.array(['hello', 'world'])
result = np.char.upper(str1)
print(result)
# 输出:['HELLO' 'WORLD']
import numpy as np
str1 = np.array(['hello world', 'numpy array'])
result = np.char.split(str1)
print(result)
# 输出:[list(['hello', 'world']) list(['numpy', 'array'])]
import numpy as np
str1 = np.array(['hello world', 'numpy array'])
result = np.char.replace(str1, ' ', '-')
print(result)
# 输出:['hello-world' 'numpy-array']
本文链接:http://task.lmcjl.com/news/4279.html