Python语言学习:字符串格式化 format 函数的封装

封装了一个 nx.tmpl 方法,来完成list/dict 两种情况的模板字符串操作
更新于: 2022-01-16 12:50:09

format 函数可以接受不限个参数,位置可以不按顺序

>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

针对 dict 类型

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

用nx.tmpl 封装如下

# list 类型
list_str = 'The first what you want to talk to python is: "{0} {1}"'
# dict 类型
dict_str = 'The first what you want to talk to python is: "My name is {name} and I am {age} years old"'

str1 = nx.tmpl(list_str, ['hello', 'world'])
str2 = nx.tmpl(dict_str, {'name': 'John', 'age': '25'})

'The first what you want to talk to python is: "hello world"'
'The first what you want to talk to python is: "My name is John and I am 25 years old"'

参考