Python语法:格式化输出
官网有讲到输入和输出
https://docs.python.org/zh-cn/3/tutorial/inputoutput.html
第一种:
要在字符串开头的引号/三引号前添加 f 或 F 。在这种字符串中,可以在 { 和 } 字符之间输入引用的变量,或字面值的 Python 表达式。
>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'
第二种:
字符串的 str.format() 方法需要更多手动操作。该方法也用 { 和 } 标记替换变量的位置,虽然这种方法支持详细的格式化指令,但需要提供格式化信息。
>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes 49.67%'
第三种:
字符串对象的 str.rjust() 方法通过在左侧填充空格,对给定宽度字段中的字符串进行右对齐。同类方法还有 str.ljust() 和 str.center() 。
>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # Note use of 'end' on previous line
... print(repr(x*x*x).rjust(4))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
第四种:
% 运算符(求余符)也可用于字符串格式化。给定 'string' % values,则 string 中的 % 实例会以零个或多个 values 元素替换。此操作被称为字符串插值。例如:
>>> import math
>>> print('The value of pi is approximately %5.3f.' % math.pi)
The value of pi is approximately 3.142.
相关文章
- aic准则python_Python数据科学:线性回归
- python移动app开发_神奇的Kivy,让Python快速开发移动app
- python中关于命名的例子_Python 命名规范入门实例「建议收藏」
- gyp ERR! stack Error: Can't find Python executable 'python'
- 【说站】python中类对象及类属性的介绍
- 【说站】python变量如何进行格式化输出
- 【说站】python traceback如何输出异常
- 【说站】Python方差特征过滤的实现
- python pkl文件_Python字符串格式化输出的方式包括
- python zipfile_Python 学习入门(16)—— zipfile
- python的特点和优势_Java与Python异同
- 【基础知识】为python部署第三方库(设备可联网版)
- Python 反转字符串_python输出字符串
- python判断文件后缀_Python 判断文件后缀是否被篡改
- Python应用之九九乘法表
- 新手学Python可行吗?需要什么基础?(新手学python可行吗?需要什么基础)
- 用python批量获取A股业绩预告2.0
- Python 小型项目大全 26~30
- python-Python与MongoDB数据库-使用Python执行MongoDB查询(三)
- python在windows命令行下输出彩色文字代码详解编程语言
- python操作mysql数据库的简单示例详解编程语言
- python学习Linux、Python,体验自由的乐趣(lexlinux)
- Python与MongoDB 无缝连接(python连接mongodb)
- Linux下Python编程:从入门到精通(linux下python编程)
- python实现2014火车票查询代码分享