Python字符串格式化方法有哪些及其使用注意事项?

2026-05-24 21:511阅读0评论SEO资讯
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计401个文字,预计阅读时间需要2分钟。

Python字符串格式化方法有哪些及其使用注意事项?

格式化方式1:使用f格式化字符串

示例:pythonname=Aliceage=25formatted_string=f我的名字是{name},今年{age}岁。print(formatted_string)输出:我的名字是Alice,今年25岁。

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

使用示例

# -*- coding: utf-8 -*- # @Time : 2020/4/22 22:35 # @Author : chinablue # 替换变量 name = "chinablue" # 格式化字符串 res_str = f"hello {name}" print(res_str)

注意事项

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

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

Python字符串格式化方法有哪些及其使用注意事项?

使用示例

# -*- coding: utf-8 -*- # @Time : 2020/4/22 22:35 # @Author : chinablue import string # 字典中的key为变量 d = { "name" : "chinablue" } # 替换字符串可以写成 $name 或 ${name}; 默认的定界符为$ s = string.Template("hello ${name}") # 执行字符串替换, res_str = s.substitute(d) print(res_str)

注意事项

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

本文共计401个文字,预计阅读时间需要2分钟。

Python字符串格式化方法有哪些及其使用注意事项?

格式化方式1:使用f格式化字符串

示例:pythonname=Aliceage=25formatted_string=f我的名字是{name},今年{age}岁。print(formatted_string)输出:我的名字是Alice,今年25岁。

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

使用示例

# -*- coding: utf-8 -*- # @Time : 2020/4/22 22:35 # @Author : chinablue # 替换变量 name = "chinablue" # 格式化字符串 res_str = f"hello {name}" print(res_str)

注意事项

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

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

Python字符串格式化方法有哪些及其使用注意事项?

使用示例

# -*- coding: utf-8 -*- # @Time : 2020/4/22 22:35 # @Author : chinablue import string # 字典中的key为变量 d = { "name" : "chinablue" } # 替换字符串可以写成 $name 或 ${name}; 默认的定界符为$ s = string.Template("hello ${name}") # 执行字符串替换, res_str = s.substitute(d) print(res_str)

注意事项

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易盾网络。