Python-字符串format方法指定参数

发布时间 2023-04-27 16:09:25作者: 业余砖家

一、字符串的format方法有几种指定参数的方式:
(1)默认方式—传入的参数与{}一一对应
(2)命名参数
(3)未知参数{2}

二、详细描述字符串的format方法如何格式化字符串:

第一种方法:

s1 = 'Today is {},the temperature is {} degrees.'
print(s1.format('Saturday',24))

第二种方法:

s2 = 'Today is {day},the temperature is {degree} degrees.'
print(s2.format(degree = 30,day = 'Saturday'))

第三种方法:

s4 = Today is {week},{1},the {0} temperature is {degree} degree.'
print(s4.format('abds',1234,degree = 45,week = 'Sunday'))

 

拓展—如果是对象呢:

class Person:
def __init__(self):
self.age = 12
self.name - 'Bill'
person = Person()

s5 = "My name is {p.name},my age is {p.age}."
print(s5.format(p = person))