学习目标:
①:Python字符串格式化
- Python日常
内容展示:
①:Python字符串格式化
# 第一题:格式化字符串的方式
"""
1. 模板字符串
2.%格式化
3.字符串的format方法
4.fstring
"""
# 通过template对象封装 $放置一些占位符,并通过substitute方法用实际的值替换这些占位符
from string import Template
template1 = Template('$s是我最喜欢胡编程语言, $s非常容易学习,而且功能强大')
print(template1.substitute(s='Python'))
# Python是我最喜欢胡编程语言, Python非常容易学习,而且功能强大
print(template1.substitute(s='PHP'))
# PHP是我最喜欢胡编程语言, PHP非常容易学习,而且功能强大
template2 = Template('${h}ello world')
# print(template2.substitute(hello='abc'))
print(template2.substitute(h='abc'))
# abcello world
template3 = Template('$dollar$$相当于$pounds英镑')
print(template3.substitute(dollar=20, pounds=16))
# 20$相当于16英镑
data = {}
data['dollar'] = 30
data['pounds'] = 25
print(template3.substitute(data))
# 30$相当于25英镑
总结:
1.
模板字符串是Template类封装的一个字符串,可以用 $指定占位符,并使用subtitute方法替换掉这些占位符
- CSDN Python日常 第【3】1 篇
- 下一篇链接