2007-06-21

 

Python Cookbook 1.17 在Python2.4(2.5)中进行字符串替换

需求:

和上一节一样,给定一个字符串和一个字典,需要在字符串中替换指定字串,并用字典中的字符串进行替换.

讨论:

在Python2.4中,提供了string.Template类来实现这个功能.下面是一个例子:

import string
# make a template from a string where some identifiers are marked with $
new_style = string.Template('this is $thing')
# use the substitute method of the template with a dictionary argument:
print new_style.substitute({'thing':5})      # emits: this is 5
print new_style.substitute({'thing':'test'}) # emits: this is test
# alternatively, you can pass keyword-arguments to 'substitute':
print new_style.substitute(thing=5)          # emits: this is 5
print new_style.substitute(thing='test')     # emits: this is test

在Python2.3中,实现上面的需求稍微有些复杂:

old_style = 'this is %(thing)s'

需要将变量用小括号括起来,在进行替换的时候,使用%,后面跟着要替换的字典.

print old_style % {'thing':5}      # emits: this is 5
print old_style % {'thing':'test'} # emits: this is test

这样的代码在2.4中依然能够工作,而且2.4提供了更简便的方法:string.Template.
当构造template实例的时候,需要用$标识要替换的变量,后面可以直接跟上变量名,或者数字,还有大括号括起来的变量.下面是一个例子:

form_letter = '''Dear $customer,
I hope you are having a great time.
If you do not find Room $room to your satisfaction,
let us know. Please accept this $$5 coupon.
            Sincerely,
            $manager
            ${name}Inn'''
letter_template = string.Template(form_letter)
print letter_template.substitute({'name':'Sleepy', 'customer':'Fred Smith',
                                  'manager':'Barney Mills', 'room':307,
                                 })

下面是输出:

Dear Fred Smith,
I hope you are having a great time.
If you do not find Room 307 to your satisfaction,
let us know. Please accept this $5 coupon.
            Sincerely,
            Barney Mills
            SleepyInn

有时,最方便的方法是使用substitute提供的locals()方式,可以直接用本地变量字典中的变量进行替换:

msg = string.Template('the square of $number is $square')
for number in range(10):
    square = number * number
    print msg.substitute(locals( ))

另外一种方式是将关键字做为参数,而不是使用字典:

msg = string.Template ('the square of $number is $square')
for i in range(10):
    print msg.substitute(number=i, square=i*i)

当然,也可以同时使用字典和参数:

msg = string.Template('the square of $number is $square')
for number in range(10):
    print msg.substitute(locals( ), square=number*number)

为了防止参数形式和字典形式冲突,参数形式的优先级更高一些:

msg = string.Template('an $adj $msg')
adj = 'interesting'
print msg.substitute(locals( ), msg='message')
# emits an interesting message

相关说明:

substitute(self, *args, **kws) unbound string.Template method

标签:


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?