转载自:http://www.cnblogs.com/coderzh/archive/2008/05/04/1181462.html
Python中按一定的格式取出某字符串中的子字符串,使用struck.unpack是非常高效的。
1. 设置fomat格式,如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
1. 设置fomat格式,如下:
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--># 取前5个字符,跳过4个字符,再取3个字符
format = '5s 4x 3s'
2. 使用struck.unpack获取子字符串
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->import struct
print struct.unpack(format, 'Test astring')
#('Test', 'ing')
来个简单的例子吧,有一个字符串'He is not very happy',处理一下,把中间的not去掉,然后再输出。
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->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
作者:CoderZh(CoderZh的技术博客 - 博客园)
微博:http://t.sina.com.cn/coderzh
出处:http://coderzh.cnblogs.com
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。