Python中按一定的格式取出某字符串中的子字符串,使用struck.unpack是非常高效的。
1. 设置fomat格式,如下:
Python天天美味(13) - struct.unpack# 取前5个字符,跳过4个字符,再取3个字符
Python天天美味(13) - struct.unpack
format = '5s 4x 3s'

2. 使用struck.unpack获取子字符串
Python天天美味(13) - struct.unpackimport struct
   print
 struct.unpack(format, 'Test astring')
Python天天美味(13) - struct.unpack
#('Test', 'ing')

来个简单的例子吧,有一个字符串'He is not very happy',处理一下,把中间的not去掉,然后再输出。
Python天天美味(13) - struct.unpackimport struct
Python天天美味(13) - struct.unpacktheString 
= 'He is not very happy'
Python天天美味(13) - struct.unpackformat 
= '2s 1x 2s 5x 4s 1x 5s'
Python天天美味(13) - struct.unpack
print ' '.join(struct.unpack(format, theString))

输出结果:

He is very happy

 

Python 天天美味系列(总)

Python 天天美味(11) - 可爱的大小写
Python 天天美味(12) - 条件判断的缩写 

Python 天天美味(13) - struct.unpack   

Python 天天美味(14) - splitlines  

Python 天天美味(15) - Python正则表达式操作指南(re使用)(转) 

...

相关文章:

  • 2021-08-03
  • 2021-12-27
  • 2021-06-13
  • 2022-01-28
  • 2021-05-28
  • 2021-12-13
  • 2021-06-25
  • 2021-12-15
猜你喜欢
  • 2021-10-07
  • 2021-08-11
  • 2021-10-11
  • 2021-08-17
  • 2021-08-15
相关资源
相似解决方案