Python中的字符串模板类

在String模块中,Template类允许我们为输出规范创建简化的语法。该格式使用由$构成的占位符名和有效的Python标识符(字母数字字符和下划线)。在占位符周围加上大括号,可以让占位符后面有更多的字母数字字母,中间没有空格。写入$$将创建一个转义$。

null

Python字符串模板:

Python字符串模板是通过将模板字符串传递给其构造函数来创建的。它支持基于$的替换。这个类有两个关键方法:

  • 替换(映射,**KWD): 该方法使用字典执行替换,其过程类似于基于键的映射对象。关键字参数也可以用于相同的目的。如果基于键的映射和关键字参数具有相同的键,它会抛出 打字错误 .如果缺少密钥,则返回 键错误 .
  • 安全替代品(地图,**KWD): 此方法的行为类似于替代方法,但它不会抛出错误 键错误 如果缺少一个键,它会在结果字符串中返回一个占位符。

当字典或关键字参数中未提供占位符时,substitute()方法会引发KeyError。对于邮件合并样式的应用程序,用户提供的数据可能不完整,而safe_substitute()方法可能更合适——如果缺少数据,它将保持占位符不变:

下面是几个简单的例子。 例1:

Python3

# A Simple Python template example
from string import Template
# Create a template that has placeholder for value of x
t = Template( 'x is $x' )
# Substitute value of x in above template
print (t.substitute({ 'x' : 1 }))


输出:

x is 1

下面是另一个例子,我们从列表中导入学生的姓名和分数,并使用模板打印它们。 例2:

Python3

# A Python program to demonstrate the
# working of the string template
from string import Template
# List Student stores the name and marks of three students
Student = [( 'Ram' , 90 ), ( 'Ankit' , 78 ), ( 'Bob' , 92 )]
# We are creating a basic structure to print the name and
# marks of the students.
t = Template( 'Hi $name, you have got $marks marks' )
for i in Student:
print (t.substitute(name = i[ 0 ], marks = i[ 1 ]))


输出:

Hi Ram, you have got 90 marksHi Ankit, you have got 78 marksHi Bob, you have got 92 marks

下面的示例显示了安全替换方法的实现。 例3:

Python3

from string import Template
template = Template( '$name is the $job of $company' )
string = template.safe_substitute(name = 'Raju Kumar' ,
job = 'TCE' )
print (string)


输出:

Raju Kumar is the TCE of $company

请注意,我们没有为“$company”占位符提供任何数据,但它不会抛出错误,而是将占位符作为字符串返回,如上所述。

打印模板字符串

模板对象的“template”属性可用于返回模板字符串,如下所示: 例子:

Python3

t = Template( 'I am $name from $city' )
print ( 'Template String =' , t.template)


输出:

Template String = I am $name from $city 

逃逸美元标志

这个 $$ 可以用来逃跑 $ 并将其视为字符串的一部分。 例子:

Python3

template = Template( '$$ is the symbol for $name' )
string = template.substitute(name = 'Dollar' )
print (string)


输出:

$ is the symbol for Dollar 

${Identifier}

${Identifier}的工作原理与$Identifier类似。当有效的标识符字符跟在占位符后面,但不是占位符的一部分时,它很方便。 例子:

Python3

template = Template( 'That $noun looks ${noun}y' )
string = template.substitute(noun = 'Fish' )
print (string)


输出:

That Fish looks Fishy

该模板的另一个应用是将程序逻辑与多种输出格式的细节分离。这使得用自定义模板替换XML文件、纯文本报告和HTML web报告成为可能。 请注意,还有其他方法可以打印格式化输出,如%d表示整数,%f表示浮点等(请参阅 (详情请参阅) 参考: https://docs.python.org/3.3/tutorial/stdlib2.html

本文由 悉达思·拉尔瓦尼。 如果你喜欢GeekSforgeks,并且想贡献自己的力量,你也可以写一篇文章,然后把你的文章邮寄给评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享