关键词

NumPy最常用的8个字符串处理函数

NumPy 提供了许多字符串处理函数,它们被定义在用于处理字符串数组的 numpy.char 这个类中,这些函数的操作对象是 string 或者 unicode 字符串数组。

下面是最常用的8个字符串处理函数:

np.char.add():将两个字符串连接起来

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']

np.char.center():将字符串居中,两侧用指定字符填充


import numpy as np

str1 = np.array(['hello', 'world'])
result = np.char.center(str1, 20, '-')
print(result)
# 输出:['-------hello--------' '-------world--------']

np.char.capitalize():将字符串首字母大写


import numpy as np

str1 = np.array(['hello', 'world'])
result = np.char.capitalize(str1)
print(result)
# 输出:['Hello' 'World']

np.char.lower():将字符串中所有字母变为小写


import numpy as np

str1 = np.array(['HELLO', 'World'])
result = np.char.lower(str1)
print(result)
# 输出:['hello' 'world']

np.char.upper():将字符串中所有字母变为大写


import numpy as np

str1 = np.array(['hello', 'world'])
result = np.char.upper(str1)
print(result)
# 输出:['HELLO' 'WORLD']

np.char.split():将字符串以指定分隔符分割成数组


import numpy as np

str1 = np.array(['hello world', 'numpy array'])
result = np.char.split(str1)
print(result)
# 输出:[list(['hello', 'world']) list(['numpy', 'array'])]

np.char.replace():将字符串中的指定字符替换为其他字符


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

展开阅读全文