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.
相关文章
- jupyter运行python代码_pycharm运行jupyter
- python skitlearn_Python sklearn
- python编程是啥-Python编程「建议收藏」
- python格式化转换_Python进制转换format格式化[通俗易懂]
- python的random()函数用法_Python随机函数random用法示例
- Python入门系列(十一)一篇搞定python操作MySQL数据库
- 【说站】Python装饰器的应用场景
- python zipfile_Python 学习入门(16)—— zipfile
- 用Python批处理指定数据-以WRF输出结果为例演示按照指定维度合并(附示例代码)
- python抛出异常写法_零基础学 Python(32):如何抛出和捕获异常?「建议收藏」
- Python 命令行模块使用技巧
- python学习 异常详解编程语言
- Python输出函数print()总结(python print())详解编程语言
- Linux下使用Python开发体验之旅(linux使用python)
- Linux中如何离开Python环境(linux怎么退出python)
- Linux Python:开启互联网新时代(linux python)
- python输出一个两行字符的变量
- 简单的Python抓taobao图片爬虫