Python文本处理(2)

访问子字符串(获取记录中某些字段的数据)

解决方法:

切片,但只能取得一个字段 

theline='I Love Python'
afield=theline[2:6]
print afield

结果
Love
如果需要考虑字段的长度,使用struct.unpack 
# -*- coding:gb2312 -*-
import struct
baseformat='1s 6x 6s'
#首先,baseformat制定了该如何对字符串进行分组,x代表跳过,s代表取出
#所以上面的代码表示拿走1个字符,跳过6个字符,拿走6个字符
theline='I Love Python So Much'
numremain=len(theline)-struct.calcsize(baseformat)
#当然,theline的字符串的长度要大于6+6+1的长度,所以需要计算剩余还有多少字符串
format='%s %ds' %(baseformat,numremain)
#重新进行分组,现在就包括了最后剩余的那部分字符串
l,s1,s2=struct.unpack(format,theline)
#用format和theline就可以进行unpack操作了
print l,s1,s2
如果想要获得5个字节一组的数据,使用带有列表推导式的切片方法 
theline='I Love Python So Much'
fivers=[theline[k:k+5] for k in xrange(0,len(theline),5)]
print fivers

结果
['I Lov', 'e Pyt', 'hon S', 'o Muc', 'h']


替换字符串中的子串

解决方案: 

def expand(format, d, marker='"', safe=False):
    if safe:
        def lookup(w): return d.get(w, w.join(marker*2))
    else:
        def lookup(w): return d[w]
    parts = format.split(marker)
    parts[1::2] = map(lookup, parts[1::2])
    return ''.join(parts)
if __name__ == '__main__':
    print expand('just "a" test', {'a': 'one'})

在Python2.4以后,可以采用string.Template类来完成该任务 

# -*- coding:gb2312 -*-
import string
#从字符串生成模板,其中标识符被$标记
new_style=string.Template('this is $thing')
#给模板的substitute方法传入一个字典参数
print new_style.substitute({'thing':5})
print new_style.substitute({'thing':'test'})
#也可以传递关键字参数
print new_style.substitute(thing=5)
print new_style.substitute(thing='test')

结果
this is 5
this is test
this is 5
this is test

在Python2.3中,可以采用如下的方法: 

# -*- coding:gb2312 -*-
old_style='this is %(thing)s'
#标识符被放在括号中,需要使用%操作符,右边放上字典
print old_style % {'thing':5}
print old_style % {'thing':'test'}
该方法在Python2.4中同样可以使用,但简洁程度不如新的方法







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值