~玉米糊~
慢慢来,也会很快。 非宁静无以志学,学什么都一样,慢慢打基础,找规律、认真、坚持,其余的交给时间。

1. 在python语言中有多少种格式化字符串的方法?

1. %格式化

2. 模板字符串

3. 字符串的format方法

4. fstring

 

2. 请解释什么是模板字符串,如何使用?

通过Template对象封装 $放置一些占位符,并通过substitute方法用实际的值替换这些占位符

from string import Template
template1 = Template('$s是我最喜欢的编程语言,$s非常容易学校,而且功能强大')
print(template1.substitute(s = 'Python'))
print(template1.substitute(s = 'PHP'))

template2 = Template('$hello world')
print(template2.substitute(hello = 'abc'))

# {}命名
template2 = Template('${h}ello world')
print(template2.substitute(h = 'abc'))

# $$ 输出$
template3 = Template('$dollar$$相当于多少$pounds英镑')
print(template3.substitute(dollar=20, pounds=16))

# 使用字典传参
data = {}
data['dollar'] = 30
data['pounds'] = 25
print(template3.substitute(data))

  

Python是我最喜欢的编程语言,Python非常容易学校,而且功能强大
PHP是我最喜欢的编程语言,PHP非常容易学校,而且功能强大
abc world
abcello world
20$相当于多少16英镑
30$相当于多少25英镑

posted on 2022-04-19 19:40  yuminhu  阅读(26)  评论(0编辑  收藏  举报