365Tools
    发布时间:2024-03-04 16:30:02
NumPy 提供了许多字符串处理函数,它们被定义在用于处理字符串数组的 numpy.char 这个类中,这些函数的操作对象是 string_ 或者 unicode_ 字符串数组。如下表所示:| 函数名称 | 描述 | 
|---|---|
| add() | 对两个数组相应位置的字符串做连接操作。 | 
| multiply() | 返回多个字符串副本,比如将字符串“ hello”乘以3,则返回字符串“ hello hello hello”。 | 
| center() | 用于居中字符串,并将指定的字符,填充在原字符串的左右两侧。 | 
| capitalize() | 将字符串第一个字母转换为大写。 | 
| title() | 标题样式,将每个字符串的第一个字母转换为大写形式。 | 
| lower() | 将数组中所有的字符串的大写转换为小写。 | 
| upper() | 将数组中所有的字符串的小写转换为大写。 | 
| split() | 通过指定分隔符对字符串进行分割,并返回一个数组序列,默认分隔符为空格。 | 
| splitlines() | 以换行符作为分隔符来分割字符串,并返回数组序列。 | 
| strip() | 删除字符串开头和结尾处的空字符。 | 
| join() | 返回一个新的字符串,该字符串是以指定分隔符来连接数组中的所有元素。 | 
| replace() | 用新的字符串替换原数组中指定的字符串。 | 
| decode() | 用指定的编码格式对数组中元素依次执行解码操作。 | 
| encode() | 用指定的编码格式对数组中元素依次执行编码操作。 | 
import numpy as np print(np.char.add(['welcome','url'], [' to C net','is www.365tools.cn'] ))输出结果:
['welcome to C net' 'url is www.365tools.cn']
import numpy as np
print (np.char.multiply('www.365tools.cn',3))
输出结果:
www.365tools.cn www.365tools.cn www.365tools.cn
np.char.center(string, width, fillchar)
string: 代表字符串,width: 表示长度,fillchar: 要填充的字符
import numpy as np  
print(np.char.center("c.bianchneg.net", 20, '*'))  
输出如下所示:**c.bianchneg.net***
import numpy as np
print (np.char.capitalize('python'))
输出结果:Python
import numpy as np  
print(np.char.title("welcome to china")) 
输出结果Welcome To China
import numpy as np  
print(np.char.lower("WELCOME TO MYHOME")) 
输出结果:welcome to myhome
import numpy as np
print(np.char.upper("Welcome To Python")) 
输出结果如下:WELCOME TO JAVATPOINT
import numpy as np  
print(np.char.split("Welcome To Python"),sep = " ")  
输出结果
['Welcome', 'To', 'Python']
import numpy as np  
print("Splitting the String line by line..") 
print(np.char.splitlines("Welcome\nTo\nPython"))  
输出结果:
['Welcome', 'To', 'Python']
import numpy as np  
print("原字符串:",str)  
str = "     welcome to Python     " 
print(np.char.strip(str))  
输出结果:原字符串: welcome to Python welcome to Python
import numpy as np
print (np.char.join(':','Love'))
#也可指定多个分隔符
print (np.char.join([':','-'],['Love','Python']))
输出结果:
L:o:v:e ['L:o:v:e' 'P-y-t-h-o-n']
import numpy as np 
str = "Welcome to China" 
print("原字符串:",str) 
#更改后字符串
print(np.char.replace(str, "Welcome to","Hello"))  
输出结果:
原字符串: Welcome to China Hello China
utf-8 的形式进行编码与解码,示例如下:
import numpy as np 
#cp500国际编码
encode_str = np.char.encode("Welcome to China", 'cp500') 
decode_str =np.char.decode(encode_str, 'cp500') 
print(encode_str) 
print(decode_str)  
输出结果:
b'\xa6\x85\x93\x83\x96\x94\x85@\xa3\x96@\xc3\x88\x89\x95\x81' Welcome to China