Chinaunix首页 | 论坛 | 博客
  • 博客访问: 216211
  • 博文数量: 39
  • 博客积分: 945
  • 博客等级: 准尉
  • 技术积分: 532
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-04 17:25
文章分类

全部博文(39)

文章存档

2012年(39)

我的朋友

分类: Python/Ruby

2012-05-24 11:16:40

源于Python cookbook 记录下来,以免以后忘记了。

1. 设置fomat格式,如下:

点击(此处)折叠或打开

  1. # 取前5个字符,跳过4个字符华,再取3个字符
  2. format = '5s 4x 3s'
2. 使用struck.unpack获取子字符串

点击(此处)折叠或打开

  1. In [12]: format = '5s 4x 3s'
  2. In [13]: import struct
  3. In [14]: struct.unpack(format,"hello Python")
  4. Out[14]: ('hello', 'hon')
来个简单的例子吧,有一个字符串'He is not very happy',处理一下,把中间的not去掉,然后再输出。

点击(此处)折叠或打开

  1. import struct
  2. theString = 'He is not very happy'
  3. format = '2s 1x 2s 5x 4s 1x 5s'
  4. print ' '.join(struct.unpack(format, theString))
2 为了处理超出baseformat字符串长度,解决方法如下:
包含其他部分

点击(此处)折叠或打开

  1. import struct
  2. baseformat = '5s 3x 8s 8s'
  3. numremain = len(theline) - struct.calcsize(baseformat)
  4. format = "%s %ds" %(baseformat, numremain)
  5. l, s1, s2, t = struct.unpack(format, theline)
取消其他部分

点击(此处)折叠或打开

  1. struct.unpack(baseformat, theString[:struct.calcsize(format)])


阅读(1072) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~