栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


  • CSDN Python日常 第【3】4 篇
  • 下一篇链接
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1005283.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号