python之字符串format()方法

format()方法就是格式化指定的值,然后再将其插入字符串的占位符内

占位符用大括号{}来定义哈,可以使用命名索引{sws}、编号索引{0}、甚至空的占位符{}来标识占位符。

语法就是

string.format(value1, value2...)

话不多说,来看代码实在点

sws_1 = "My name is {name}, I'm {age}".format(name="Slowsnail", age=20)
sws_2 = "My name is {0}, I'm {1}".format("Slowsnail", 20)
sws_3 = "My name is {}, I'm {}".format("Slowsnail", 20)

print(sws_1, '\n', sws_2, '\n', sws_3)

结果肯定大家都已经想到啦

My name is Slowsnail, I'm 20 
 My name is Slowsnail, I'm 20 
 My name is Slowsnail, I'm 20

更多占位符的使用技巧,推荐大家看看https://www.w3school.com.cn/python/ref_string_format.asp

posted @   放氮气的蜗牛  阅读(72)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示