Python format() 基础

Python format() 高级。

 

format格式化

# ^,<,>分别表示居中,左对齐,右对齐;冒号后面是要填充的字符,只能是一个字符,不指定默认为空格
print('{:*^60}'.format('token & word mapping review:'))

 

print('{:.2f}'.format(3.1415926))
# 使用大括号{}转义大括号
print('{}对应的位置是:{{0}}'.format('runoob'))
runoob对应的位置是:{0}

 

format函数接受不限个参数,位置不按顺序

print('{}{}'.format('hello', 'world'))    # 不设定位置,默认按顺序
print('{0},{1}'.format('hello', 'world'))  # 设定顺序
print('{1}-{0}-{1}'.format('hello', 'world'))
helloworld
hello,world
world-hello-world

format设置参数

print('网站名:{name}, 地址{url}'.format(name='菜鸟教程',url='www.runoob.com'))
# 通过字典设置参数
site = {'name':'菜鸟教程', 'url':'www.runoob.com'}
print('网站名:{name}, 地址:{url}'.format(**site))
网站名:菜鸟教程, 地址:www.runoob.com

# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print('网站名:{0[0]}, 地址:{0[1]}'.format(my_list))

 注意:列表索引设置参数,‘0’是必须的。

 

posted @   做梦当财神  阅读(282)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示