Python模板字符串Template

2023-05-16

文章目录

  • 一、Template说明
  • 二、Python字符串替换的几种方法
    • 1.适用于变量少的单行字符串替换
    • 2.字符串命名格式化符替换
    • 3.模版方法替换

一、Template说明

1.定义字符串
根据需要,设置字符串中需要替换的字符以${变量名称}的形式显示。

  • 示例:instances、modelName、index、modelType
# 文本结构
start = '''<?xml version="1.0" encoding="UTF-8"?>'''
content = '''<Instances>${instances}</Instances>'''
instance = '''<Instance id="${modelName}_${index}" type="${modelType}"/>'''

2.转换字符串模板
将已定义的字符串使用Template(str)的形式转换为字符串模板。

# 转换字符串模板
instance_template = Template(instance)
content_template = Template(content)

3.声明字典变量

  • 使用字典存储需替换的变量名称及目标替换值,采用{“key”:“value”}的形式。
# 声明字典变量,可同时设置初始值
params = {"times":10, "modelName":"car", "modelType":"1000"}

# 在循环过程中每次更新index的值
for index in range(1, params["times"] + 1):
    params["index"] = index

4.替换字符串模板

  • 采用substitute(dict)方法可一次性替换模板中的所有变量。
    注意:采用substitute替换时需确认所有待替换变量都在字典中存在!或者,也可以选择使用safe_substitute进行替换。
# 变量声明
instances = ''

# 循环造数据
for index in range(1, params["times"] + 1):
    params["index"] = index
    tmpInstance = instance_template.substitute(params)
    instances = instances + tmpInstance

# 替换中心内容
params["instances"] = instances
content = content_template.substitute(params)

#!/usr/bin/env python3 

import os
from string import Template
from xml.dom import minidom

# 参数含义
# filepath: 文本存储路径
# way: 写入方式 w重写 at追加
# content: 文本内容
def make_content(filepath=None, way=None, content=None):
  os.makedirs(os.path.dirname(filepath), exist_ok=True)
  file = open(filepath, way, encoding="utf-8")
  file.write(content)
  file.close()

# 文本结构
start = '''<?xml version="1.0" encoding="UTF-8"?>'''
content = '''<Instances>${instances}</Instances>'''
instance = '''<Instance id="${modelName}_${index}" type="${modelType}"/>'''

# 转换字符串模板
instance_template = Template(instance)
content_template = Template(content)

# 变量声明
instances = ''
filepath = os.getcwd() + "/demo.xml"
params = {"times":10, "modelName":"car", "modelType":"1000"}

# 循环造数据
for index in range(1, params["times"] + 1):
    params["index"] = index
    tmpInstance = instance_template.substitute(params)
    instances+= tmpInstance

# 替换中心内容
params["instances"] = instances
content = content_template.substitute(params)

# 拼接完整内容,并写入文件
outer = start + content
outer_xml = minidom.parseString(outer)
outer_prettyxml = outer_xml.toprettyxml()
# print(outer_prettyxml)
make_content(filepath, "w", outer_prettyxml)
print(filepath)


结果:

<?xml version="1.0" ?>
<Instances>
	<Instance id="car_1" type="1000"/>
	<Instance id="car_2" type="1000"/>
	<Instance id="car_3" type="1000"/>
	<Instance id="car_4" type="1000"/>
	<Instance id="car_5" type="1000"/>
	<Instance id="car_6" type="1000"/>
	<Instance id="car_7" type="1000"/>
	<Instance id="car_8" type="1000"/>
	<Instance id="car_9" type="1000"/>
	<Instance id="car_10" type="1000"/>
</Instances>

其他eg:

>>> import string
查看string是否已经导入
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'string']
类相关文档
>>> help(string)
>>>> help(string.Template)

二、Python字符串替换的几种方法

1.适用于变量少的单行字符串替换

template = "hello %s , your website  is %s " % ("大CC","http://blog.me115.com")
print(template)

format函数的语法方式:
template = "hello {0} , your website  is {1} ".format("大CC","http://blog.me115.com")
print(template)

2.字符串命名格式化符替换

使用命名格式化符,这样,对于多个相同变量的引用,在后续替换只用申明一次即可;

template = "hello %(name)s ,your name is %(name), your website  is %(message)s" %{"name":"大CC","message":"http://blog.me115.com"}
print(template)


format函数的语法方式:
template = "hello {name} , your name is {name}, your website  is {message} ".format(name="大CC",message="http://blog.me115.com")
print(template)

3.模版方法替换

使用string中的Template方法;

  • 通过字典传递参数:
from string import Template

tempTemplate  = Template("There ${a} and ${b}")
d={'a':'apple','b':'banbana'}
print(tempTemplate.substitute(d))


或者
tempTemplate  = Template("There ${a} and ${b}")
d={'a':'apple','b':'banbana'}
print(tempTemplate.substitute(a='apple',b='banbana'))

总结:
使用$标识需替换的变量;
使用Template(str)定义字符串模板;
使用params={}字典键值对的形式定义变量及其需要替换的结果值;
使用substitute(dict)或safe_substitute(dict)方法执行替换。

参考:

  • Python字符串替换的几种方法
  • 零基础Python教程050期 模板字符串Template类使用精髓
  • python-Template字符串模板的使用
  • Template类创建模板替换字符串
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python模板字符串Template 的相关文章

  • 如何从 Python 返回 JSON 值?

    我从如下所示的 jQuery 文件发送 ajax 请求 该请求需要 JSON 格式的响应 jQuery ajax url Control getImageDetails file id currentId type GET contentT
  • 用于查找列表/集合中唯一元素的代码

    根据上面阴影部分的面积应该代表 A XOR B XOR C XOR A AND B AND C 如何将其翻译成Python代码 代码必须与上述表达式中提供的集合操作密切相关 至少这是首选 该代码必须足够通用 能够处理 3 个以上的列表 UP
  • 管理 Tweepy API 搜索

    如果这是对之前在其他地方回答过的问题的粗略重复 请原谅我 但我不知道如何使用 tweepy API 搜索功能 是否有任何有关如何使用搜索推文的文档api search 功能 有什么方法可以控制返回的推文数量 结果类型等功能 由于某种原因 结
  • 如何跳过财务图中的空日期(周末)

    ax plot date dates dates highs lows 我目前正在使用此命令来绘制财务高点和低点Matplotlib http en wikipedia org wiki Matplotlib 效果很好 但如何删除 x 轴上
  • Python pandas:删除字符串中分隔符之后的所有内容

    我有数据框 其中包含例如 vendor a ProductA vendor b ProductA vendor a Productb 我需要删除所有内容 包括 两个 以便我最终得到 vendor a vendor b vendor a 我尝
  • 检查多维 numpy 数组的所有边是否都是零数组

    n 维数组有 2n 个边 1 维数组有 2 个端点 2 维数组有 4 个边或边 3 维数组有 6 个 2 维面 4 维数组有 8 个边 ETC 这类似于抽象 n 维立方体发生的情况 我想检查 n 维数组的所有边是否仅由零组成 以下是边由零组
  • 使用 OpenCV 进行相机校准 - 如何调整棋盘方块大小?

    我正在使用 OpenCV Python 示例开发相机校准程序 来自 OpenCV 教程 http opencv python tutroals readthedocs io en latest py tutorials py calib3d
  • 获取 HTML 代码的结构

    我正在使用 BeautifulSoup4 我很好奇是否有一个函数可以返回 HTML 代码的结构 有序标签 这是一个例子 h1 Simple example h1 p This is a simple example of html page
  • Microsoft Azure 数据仓库和 SqlAlchemy

    我正在尝试使用 python 的 sqlalchemy 库连接到 microsoft azure 数据仓库 并收到以下错误 pyodbc Error HY000 HY000 Microsoft ODBC SQL Server Driver
  • 如何将字符串方法应用于数据帧的多列

    我有一个包含多个字符串列的数据框 我想使用对数据帧的多列上的系列有效的字符串方法 我希望这样的事情 df pd DataFrame A 123f 456f B 789f 901f df Out 15 A B 0 123f 789f 1 45
  • 当我打印“查询”时获取 PY_VAR1

    我正在制作一个简单的网络抓取代码 当我尝试打印一个值时 它给了我其他东西 def PeopleSearch query SearchTerm query what is query print str query SearchTerm St
  • 让 TensorFlow 在 ARM Mac 上使用 GPU

    我已经安装了TensorFlow在 M1 上 ARM Mac 根据这些说明 https github com apple tensorflow macos issues 153 一切正常 然而 模型训练正在进行CPU 如何将培训切换到GPU
  • Python:使用for循环更改变量后缀

    我知道这个问题被问了很多 但到目前为止我无法使用 理解答案 我想改变for循环中变量的后缀 我尝试了 stackoverflow 搜索提供的所有答案 但很难理解提问者经常提出的具体代码 因此 为了清楚起见 我使用一个简单的示例 这并不意味着
  • 如何使用 Ajax 在 Flask 中发布按钮值而不刷新页面?

    我有一个问题 当我单击 Flask 应用程序中的按钮时 我想避免重新加载 我知道有 Ajax 解决方案 但我想知道如何将我的按钮链接到 ajax 函数以发布按钮值并运行链接到其值的 python 函数 这是我的 html 按钮 div di
  • Python中的MariaDB连接器无法连接到远程服务器

    我使用与远程 Mariadb 服务器的连接已有几个月了 今天 无法再通过 macOS 上的 python mariadb 模块和 mariadb 连接器建立连接 基本安装如下 brew install mariadb connector c
  • Java 相当于 Python 的 urllib.urlencode(基于 HashMap 的 UrlEncode)

    From https stackoverflow com questions 2018026 should i use urllib or urllib2 2018103 2018103 Java 中 Python 的 urllib url
  • Python 可以替代 Java 小程序吗?

    除了制作用于物理模拟 如抛射运动 重力等 的教育性 Java 小程序之外 还有其他选择吗 如果你想让它在浏览器中运行 你可以使用PyJamas http pyjs org 这是一个 Python 到 Javascript 的编译器和工具集
  • Python模糊字符串匹配作为相关样式表/矩阵

    我有一个文件 其中包含 x 个字符串名称及其关联的 ID 本质上是两列数据 我想要的是一个格式为 x by x 的相关样式表 将相关数据作为 x 轴和 y 轴 但我想要 fuzzywuzzy 库的函数 fuzz ratio x y 作为输出
  • 将字典写入 csv 时遇到问题,其中键作为标题,值作为列

    我有一本字典 看起来像 mydict foo 1 2 bar 3 4 asdf 5 6 我正在尝试将其写入 CSV 文件 使其看起来像 foo bar asdf 1 3 5 2 4 6 我花了最后一个小时寻找解决方案 我发现的最接近的解决方
  • 将自定义属性添加到 Tk 小部件

    我的主要目标是向小部件添加隐藏标签或字符串之类的内容 以在其上保存简短信息 我想到创建一个新的自定义 Button 类 在本例中我需要按钮 它继承所有旧选项 这是代码 form tkinter import class NButton Bu

随机推荐

  • GTEST/GMOCK介绍与实战:Gtest Sample10

    文章目录 1 简介2 用法 1 简介 示例 10展示了如何使用侦听器API来实现基本内存泄漏检查 2 用法 span class token comment This sample shows how to use Google Test
  • Bitbake与Yocto

    文章目录 一 Bitbake二 Yocto 一 Bitbake xff08 1 xff09 使用教程可以参考 xff1a BitBake 实用指南 xff0c 大部分步骤跟着操作即可了解bitbake的工作流程 xff1b 他主要参考和翻译
  • 随机漫步

    span class token keyword import span numpy span class token keyword as span np span class token keyword import span rand
  • UTC时间和PTP精确时间协议

    文章目录 一 GMT二 UTC三 GMT vs UTC四 C 43 43 获得当前的UTC时间 一 GMT GMT xff08 Greenwich Mean Time xff09 xff0c 格林威治平时 xff08 也称格林威治时间 xf
  • AutoSar系列之:AutoSar发展

    文章目录 一 Autosar成员二 Autosar历史发展三 使用Autosar前的状态1 原始状态2 进阶状态 四 使用Autosar后的状态1 软硬件隔离2 Autosar优势 一 Autosar成员 二 Autosar历史发展 三 使
  • AutoSar系列之:AutoSar概述

    文章目录 一 Autosar是什么二 架构 一 Autosar是什么 RTE xff1a 用与传递应用层软件和基础软件从之间的信号的 xff1b 隔离应用软件层和基础软件层 xff1b 其中一个层修改了 xff0c 不会影响另外一个层 xf
  • Autosar系列之Appl概述

    文章目录 一 Appl的组成1 SWC通信2 SWC分配 一 Appl的组成 SWC xff1a 应用软件组件 Autosar接口 xff1a SWC之间连接的端口 Runnable xff1a 可运行实体 xff0c SWC里面的一些函数
  • Autosar系列之SWC类型

    文章目录 一 原子级SWC二 集合级SWC三 特殊的SWC 一 原子级SWC 含义 xff1a 不可拆解的SWC 二 集合级SWC eg xff1a 将相似的功能放在一起 三 特殊的SWC IoHwAb xff0c Cdd 在原有的Auto
  • 汽车操作系统

    文章目录 一 汽车控制器类型二 Hypervisor三 QNX Linux Andorid四 Automotive Grade Linux 系统 xff08 AGL xff09 1 介绍2 IVI市场现状3 系统构建 xff08 1 xff
  • Autosar系列之Ports类型

    文章目录 一 接口二 接口类型三 S R接口四 C S 接口 一 接口 接口是连接2个SWC通信的 二 接口类型 三 S R接口 发送 接受数据传输接口 一般通过全局变量才传递 四 C S 接口 客户 服务接口 xff1b 通过函数Runn
  • Autosar系列之Runnable可运行实体

    文章目录 一 RUnnable Entity 一 RUnnable Entity 可运行实体 xff0c 其实就是 C文件内的函数而已 一个SWC可以包含多个Runnable Entity xff0c 就是一个 C文件中可以包含多个函数 x
  • Autosar系列之RTE

    文章目录 一 RTE二 RTE功能 一 RTE RTE Run TIme Environment 是Autosar体系结构的核心 RTE是Autosar软件架构中 xff0c 介于应用层和基础软件层之间 xff0c 是Autosar虚拟功能
  • Autosar系列之Autosar应用层整体入门

    文章目录 一 整个功能示意图二 软件组件SWC分类三 SWC组件 xff1a ports1 发送 接收端口Sender Receiver2 客户端 服务端端口Client Server 四 可运行实体Runnables五 BSW1 微控制器
  • ubuntu下mysql数据库的设置

    gt su root gt mysql span class token operator span u root span class token operator span p gt show databases span class
  • Python装饰器Decorators

    文章目录 一 功能二 64 语法糖三 args kwargs四 带参数的装饰器五 类装饰器六 装饰器顺序 一 功能 装饰器本质上是一个 Python 函数或类 xff0c 它可以让其他函数或类在不需要做任何代码修改的前提下增加额外功能 xf
  • Autosar系列之Developer工具

    文章目录 一 什么是DaVinci Developer xff1f 二 DaVinci Developer Workspace三 Software Conponent xff08 SWC xff09 Design 一 什么是DaVinci
  • vscode中调试rust程序

    文章目录 一 vscode运行和调式rust程序二 常见问题1 rust Request textDocument formatting failed 2 cargo命令3 使用rust gdb调试rust程序4 cargo build太慢
  • Available-Python-Tuf

    文章目录 一 Pyhon tuf二 安装方法三 启动四 一个可用的Python Tuf 一 Pyhon tuf 1 github link 向该Pyhton tuf的repo server上传包不会持久化保存到本地 xff0c 是个demo
  • 现代C++教程2023

    文章目录 2 C 43 43 默认实参21 模板模板形参22 C 43 43 11形参包24 std nothrow25 std call once与pthread once 2 C 43 43 默认实参 21 模板模板形参 模板参数 xf
  • Python模板字符串Template

    文章目录 一 Template说明二 Python字符串替换的几种方法1 适用于变量少的单行字符串替换2 字符串命名格式化符替换3 模版方法替换 一 Template说明 1 定义字符串 根据需要 xff0c 设置字符串中需要替换的字符以