python字符串格式化 学习二

模板字符串:

string模板提供另外一种格式化值的方法:模板字符串。它的工作方式类似于很多Unix Shell里的变量替换。

 

>>> from string import Template
>>> s = Template('$X. glorious $X!')  
>>> s.substitute(X='slurm') 
'slurm. glorious slurm!'

 

如果替换字段是单词的一部分,那么参数名就必须用括号括起来,从而精确指明结尾:

 

>>> s = Template("It's ${X}tastic!")
>>> s.substitute(X='slurm')
"It's slurmtastic!"

 

可以用$$插入美元符:

 

>>> s = Template("Make $$ selling $X!")
>>> s.substitute(X='slurm') 
'Make $ selling slurm!'

 

除了关键字参数之外,还可以使用字典变量提供值/名称对

 

>>> s = Template("A $thing must never $action.")
>>> d = {}
>>> d['thing'] = 'gentleman'  
>>> d['action'] = 'show his socks'
>>> s.substitute(d) 
'A gentleman must never show his socks.'

 

 

 

 

 

 

 

 

posted on 2012-10-12 10:41  mingaixin  阅读(364)  评论(0编辑  收藏  举报