当前位置: 首页 > 图文教程 > 脚本技术 > Python > Python struct.unpack

Python
Python 可爱的大小写
Python 条件判断的缩写方法
Python struct.unpack
Python splitlines使用技巧
比较详细Python正则表达式操作指南(re使用)
Python 过滤字符串的技巧,map与itertools.imap
Python open读写文件实现脚本
Python linecache.getline()读取文件中特定一行的脚本
Python 时间处理datetime实例
Python 命令行参数sys.argv
Python httplib,smtplib使用方法
Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)
Python enumerate遍历数组示例应用
Python 初始化多维数组代码
Python 深入理解yield
Python __getattr__与__setattr__使用方法
Python 网络编程起步(Socket发送消息)
Python urlopen 使用小示例
Python 调用VC++的动态链接库(DLL)
新手该如何学python怎么学好python?

Python struct.unpack


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-11   浏览: 599 ::
收藏到网摘: n/a

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