0
点赞
收藏
分享

微信扫一扫

27 - python字符串格式化


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

  • % 格式化
  • 模板字符串
  • 字符串的 format 方法
  • fstring

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

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

template1 = Template('$s是世界上最好的编程语言, $s非常容易学习,而且功能强大')
print(template1.substitute(s = 'Python'))
print(template1.substitute(s = 'PHP'))

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非常容易学习,而且功能强大
20$相当于多少16英镑
30$相当于多少25英镑

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

abcello world

​​28 - 使用fstring 方法格式化字符串​​


举报

相关推荐

0 条评论