Python

字符串的插值(interpolation) 具体解释


本文地址: http://blog.csdn.net/caroline_wendy/article/details/27054263


字符串的替换(interpolation), 能够使用string.Template, 也能够使用标准字符串的拼接.

string.Template标示替换的字符, 使用"$"符号, 或 在字符串内, 使用"${}"; 调用时使用string.substitute(dict)函数.

标准字符串拼接, 使用"%()s"的符号, 调用时, 使用string%dict方法.

两者都能够进行字符的替换.


代码:

# -*- coding: utf-8 -*-

'''
Created on 2014.5.26

@author: C.L.Wang

Eclipse Pydev python 2.7.5
'''

import string

values = {'var' : 'foo'}

tem = string.Template('''
Variable : $var
Escape : $$
Variable in text : ${var}iable
''')

print 'TEMPLATE:', tem.substitute(values)

str = '''
Variable : %(var)s
Escape : %%
Variable in text : %(var)siable
'''

print 'INTERPOLATION:', str%values

输出:

TEMPLATE: 
Variable : foo
Escape : $
Variable in text : fooiable

INTERPOLATION: 
Variable : foo
Escape : %
Variable in text : fooiable







原文地址:https://www.cnblogs.com/wzzkaifa/p/6872130.html