1. 字符串的format方法有几种指定参数的方法
- 默认方式(传入的参数与{} 一一对应)
- 命名参数
- 位置参数{2}
2. 请详细描述字符串的format方法如何格式化字符串
s1 = 'Today is {}, the temperature is {} degress.'
print(s1.format('Saturday', 24))
Today is Saturday, the temperature is 24 degress.
s2 = 'Today is {day}, the temperature is {degree} degress.'
print(s2.format(degree = 30, day = 'Sunday'))
Today is Sunday, the temperature is 30 degress.
s3 = 'Today is {day},{} the {} temperature is {degree}'
print(s3.format('abcd' , 12345, degree=24, day='Sunday'))
Today is Sunday,abcd the 12345 temperature is 24
s4 = 'Today is {day}, {1}, the {0} temperature is {degree} degrees.'
print(s4.format('abcd', 12345, degree=24, day='Sunday'))
Today is Sunday, 12345, the abcd temperature is 24 degrees.
class Person:
def __init__(self):
self.age = 20
self.name = 'Bill'
person = Person()
s5 = 'My name is {p.name}, my age is {p.age}'
print(s5.format(p = person))
My name is Bill, my age is 20
正文完