《Python基础》之字符串格式化输出

目录

方式一

[1、带索引 {0}](#1、带索引 {0})

[2、不带索引 { }](#2、不带索引 { })

3、{自定义变量}

方式二

方式三

控制浮点数精度


方式一

使用.format( )进行格式化

1、带索引 {0}

python 复制代码
name = 'boy'
age = 18
high = 183.55555
gender = 'man'
print('姓名是:{0},年龄是:{1},身高是:{2},性别是:{3},身高是:{2}'.format(name, age, high, gender))

输出结果为:

2、不带索引 { }

format中的数据需要按照顺序填写

python 复制代码
name = 'boy'
age = 18
high = 183.55555
gender = 'man'
print('姓名是:{},年龄是:{},身高是:{},性别是:{}'.format(name, age, high, gender))

输出结果为:

3、{自定义变量}

python 复制代码
name = 'boy'
age = 18
high = 183.55555
gender = 'man'
print('姓名是:{a},年龄是:{b},身高是:{c},性别是:{d}'.format(a=name, b=age, c=high, d=gender))

输出结果为:

方式二

%占位符输出,这种方式传参,需要考虑数据类型的问题

python 复制代码
name = 'boy'
age = 18
high = 183.55555
gender = 'man'
print('姓名是:%s,年龄是:%d,身高是:%f,性别是:%s' % (name, age, high, gender))

输出结果为:

方式三

f-{ }格式化输出

python 复制代码
name = 'boy'
age = 18
high = 183.55555
gender = 'man'
print(f'姓名是:{name},年龄是:{age},身高是:{high},性别是:{gender}')

输出结果为:

控制浮点数精度

python 复制代码
name = 'boy'
age = 18
high = 183.55555
gender = 'man'
print('身高是:{c:.2f}'.format(c=high))
print('身高是:{:.2f}'.format(high))
print('身高是:%.2f' % high)
print(f'身高是:{high:.2f}')

结果:

相关推荐
Flittly9 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling13 小时前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook17 小时前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风18 小时前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风18 小时前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei1 天前
python 抽象基类
python
用户8356290780511 天前
Python 实现 PPT 转 HTML
后端·python
zone77392 天前
004:RAG 入门-LangChain读取PDF
后端·python·面试
zone77392 天前
005:RAG 入门-LangChain读取表格数据
后端·python·agent
树獭非懒2 天前
AI大模型小白手册|Embedding 与向量数据库
后端·python·llm