~玉米糊~
慢慢来,也会很快。 非宁静无以志学,学什么都一样,慢慢打基础,找规律、认真、坚持,其余的交给时间。
随笔 - 117,  文章 - 17,  评论 - 1,  阅读 - 82072

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

1. %格式化

2. 模板字符串

3. 字符串的format方法

4. fstring

 

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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   yuminhu  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示