版权声明:随意转载嘿嘿,加一个说明就行 https://blog.csdn.net/qq_30386541/article/details/88023645
格式化字符串的函数 str.format()
基本语法:
通过 {} 和 : 来代替以前的 %
format 函数可以接受不限个参数,位置可以不按顺序。
使用举例:
# 不设置指定位置,按默认顺序
str1 = "{} {}".format("hello", "world")
print('str1 :'+str1)
# 设置指定位置
str2 = "{0} {1}".format("hello", "world")
print('str2 :'+str2)
# 设置指定位置
str3 = "{1} {0} {1}".format("hello", "world")
print('str3 :'+str3)
结果:
str1 :hello world str2 :hello world str3 :world hello world
print("姓名:{name}, 年龄 {age}".format(name="小明", age="18"))
# 通过字典设置参数
site = {"name": "小明", "age": "18"}
print("姓名:{name}, 年龄 {age}".format(**site))
# 通过列表索引设置参数
my_list = ['小明', '18']
print("姓名:{0[0]}, 年龄 {0[1]}".format(my_list)) # "0" 是必须的
结果:
姓名:小明, 年龄 18 姓名:小明, 年龄 18 姓名:小明, 年龄 18
# 向 str.format() 传入对象:
class Test(object):
def __init__(self, value):
self.value = value
my_value = Test('weew12')
print('value 为: {0.value}'.format(my_value)) # "0" 是可选的
结果:
value 为: weew12
examples = ["this is the {} line".format(number) for number in range(1, 11)]
for example in examples:
print(example)
结果:
this is the 1 line this is the 2 line this is the 3 line this is the 4 line this is the 5 line this is the 6 line this is the 7 line this is the 8 line this is the 9 line this is the 10 line
(待补充。。。)