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

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

2. 使用struck.unpack获取子字符串
import struct
   print
 struct.unpack(format, 'Test astring')
#('Test', 'ing')

来个简单的例子吧,有一个字符串'He is not very happy',处理一下,把中间的not去掉,然后再输出。
import struct
theString 
= 'He is not very happy'
format 
= '2s 1x 2s 5x 4s 1x 5s'
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使用)(转) 

...

posted @   CoderZh  阅读(5090)  评论(12)    收藏  举报
编辑推荐:
· 别做抢活的导演:代码中的抽象层次原则
· 从 Redis 客户端超时到 .NET 线程池挑战
· C23和C++26的#embed嵌入资源指南
· 「EF Core」框架是如何识别实体类的属性和主键的
· 独立开发,这条路可行吗?
阅读排行:
· 他没买 iPad,而是花了半年时间,为所有“穷学生”写了个笔记神器
· Visual Studio 现已支持新的、更简洁的解决方案文件(slnx)格式
· 从 Redis 客户端超时到 .NET 线程池挑战:饥饿、窃取与阻塞的全景解析
· 2025年中总结:我想我克服公众演讲的恐惧了,一个社恐分子突破自我的故事
· 3.1k star!推荐一款开源基于AI实现的浏览器自动化插件工具 !
点击右上角即可分享
微信分享提示