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英镑
标签:
Python 100讲
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!