python字符串的格式化

格式化方式1: 使用f""

1.1 使用示例

 1 # -*- coding: utf-8 -*-
 2 # @Time    : 2020/4/22 22:35
 3 # @Author  : chinablue
 4 
 5 # 替换变量
 6 name = "chinablue"
 7 
 8 # 格式化字符串
 9 res_str = f"hello {name}"
10 
11 print(res_str)
View Code

1.2 注意事项

  • %和format也是python常用的格式化字符串方式;
  • 如果字符串中需要显示{},则通过{{}}来转义.

格式化方式2: 使用string.Template

4.1 使用示例

 1 # -*- coding: utf-8 -*-
 2 # @Time    : 2020/4/22 22:35
 3 # @Author  : chinablue
 4 
 5 import string
 6 
 7 # 字典中的key为变量
 8 d = {
 9     "name" : "chinablue"
10 }
11 
12 # 替换字符串可以写成 $name 或 ${name}; 默认的定界符为$
13 s = string.Template("hello ${name}")
14 
15 # 执行字符串替换,
16 res_str = s.substitute(d)
17 
18 print(res_str)
View Code

4.2 注意事项

  • 占位符如果写成${}时,变量和括号之间不能有空格;
  • string.substitute()中的参数,如果字符串中未提供占位符,会抛出KeyError异常;
  • string.substitute()中的参数可以是字典或关键字参数. 如果关键字参数和字典中的key重复了,关键字参数的取值优先;
  • string.safe_substitute()中的参数,如果字符串中未提供占位符,不会抛异常;
  • 通过继承string.Template类,并覆盖delimiter变量和idpattern变量.可以自定义字符串模板.
原文地址:https://www.cnblogs.com/reconova-56/p/12782979.html