在例子中对指定的字符串:
faa5fbb5fcc5fdd5010200000028000001900000000a002d00000000017d7840000003e800005fa55fb55fc55fd5
使用了三种方法将其转换为大写字母并每隔2个字符用空格分割处理后得到一个新字符串,为:
FA A5 FB B5 FC C5 FD D5 01 02 00 00 00 28 00 00 01 90 00 00 00 0A 00 2D 00 00 00 00 01 7D 78 40 00 00 03 E8 00 00 5F A5 5F B5 5F C5 5F D5
为验证三种方法的执行效率,对原字符串扩充为其100倍长度,然后执行10000次处理,从其耗时结果上看,第一种方法最慢,第二、三种方法较好。
代码:
1 # -*- coding: utf-8 -*-# 2 3 #------------------------------------------------------------------------------- 4 # Name: MySplit 5 # Description: 将指定的字符串转换为大写字母并每隔2个字符用空格分割后得到一个新字符串 6 # Author: Administrator 7 # Date: 2018/7/6 8 #------------------------------------------------------------------------------- 9 10 import re 11 import time 12 13 #待分割字符串 14 myStr = ‘faa5fbb5fcc5fdd5010200000028000001900000000a002d00000000017d7840000003e800005fa55fb55fc55fd5‘ 15 #分割后: FA A5 FB B5 FC C5 FD D5 01 02 00 00 00 28 00 00 01 90 00 00 00 0A 00 2D 00 00 00 00 01 7D 78 40 00 00 03 E8 00 00 5F A5 5F B5 5F C5 5F D5 16 17 def mySplit1(str): 18 t=‘‘ 19 for i in range(len(str)/2): 20 t += str[2*i:2*(i+1)] + ‘ ‘ 21 t = t.upper() 22 return t 23 24 def mySplit2(str): 25 t = str.upper() 26 p = re.compile(‘.{1,2}‘) # 匹配任意字符1-2次 27 return ‘ ‘.join(p.findall(t)) 28 29 def mySplit3(str): 30 t = str.upper() 31 return ‘ ‘.join([t[2*i:2*(i+1)] for i in range(len(t)/2)]) 32 33 print(‘原始字符串:\n‘ + myStr + ‘\n‘) 34 print(‘转换后字符串:‘) 35 print(‘mySplit1: ‘ + mySplit1(myStr)) 36 print(‘mySplit2: ‘ + mySplit2(myStr)) 37 print(‘mySplit3: ‘ + mySplit3(myStr)) 38 39 print(u‘\n耗时测试:‘) 40 myStr = myStr * 100 41 for f in [mySplit1, mySplit2, mySplit3]: 42 t = time.time() 43 for i in range(10000): 44 f(myStr) 45 print(f.func_name + ‘: ‘ + str(time.time()-t) + ‘ s‘)
运行结果如下:
原文地址:https://www.cnblogs.com/luke0011/p/9278777.html
时间: 2024-10-12 04:02:07