3.4字符串format方法指定参数的方式

学习目标:

①:字符串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方法使用一对大括号 { }指定字符串需要替换的内容。在花括号中间可以使用数字,表示引用特定位置的参数值,也可以使用标识符,可以根据名字设置相应位置的占位符。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿中在线啃码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值