学习目标:
①:字符串format指定参数的方式
- Python日常
内容展示:
①:字符串format指定参数的方式
# 第一題:字符串的format方法有几种指定参数的方式
# 默认方式(传入的参数与{}一一对应)、命名参数和位置参数{2}
# 默认方式,命名参数,位置参数演示
s1 = 'Today is {}, the temperature is {} degrees'
print(s1.format('Saturday', 24))
# Today is Saturday, the temperature is 24 degrees
s2 = 'Today is {day}, the temperature is {degree} degrees'
print(s2.format(day='Saturday',degree=24 ))
# Today is Saturday, the temperature is 24 degrees
s3 = 'Today is {week},{}, the {} temperature is {degree}'
print(s3.format('adcb',1234,week='sunday', degree=30))
# Today is sunday,adcb, the 1234 temperature is 30
s4 = 'Today is {week},{1}, the {0} temperature is {degree} degree' # {1}取第二個值,{0}取第一個值
print(s4.format('abcd',1234,week='sunday',degree=43))
# Today is sunday,1234, the abcd temperature is 43 degree
class Person:
def __init__(self):
self.age = 20
self.name = 'Bill'
person = Person()
s5 = 'My name is {p.name},年齡{p.age}'
print(s5.format(p=person))
# My name is Bill,年齡20
总结:
Format方法使用一对大括号 { }指定字符串需要替换的内容。在花括号中间可以使用数字,表示引用特定位置的参数值,也可以使用标识符,可以根据名字设置相应位置的占位符。
- CSDN Python日常 第【3】4 篇
- 下一篇链接