Python format() function is used to convert given object into string representation based on the provided format specs.

Python format()函数用于根据提供的格式规范将给定的对象转换为字符串表示形式。

Python格式() (Python format())

Python format() function syntax is:

Python format()函数语法为:

format(value[, format_spec])

This function calls __format__() method of the value object. We can define this function for our custom classes to use format() function with them.

此函数调用value对象的__format __()方法。 我们可以为自定义类定义此函数,以对其使用format()函数。

Some of the format options for numbers are:

一些数字格式选项是:

  • ‘+’ – sign should be used with both positive and negative numbers.'+'–符号应同时使用正数和负数。
  • ‘-‘ – sign should be used with only negative numbers, this is the default behavior.'-'–符号只能与负数一起使用,这是默认行为。
  • % – multiplied with 100 and shown in percentage%–乘以100并以百分比显示
  • ‘b’, ‘o’, ‘x’, ‘X’ – convert integer to binary, octal and hexadecimal format. Lower case letters will be used for ‘x’ whereas upper case letters will be used with ‘X’. These are applicable only for integers.'b','o','x','X'–将整数转换为二进制,八进制和十六进制格式。 小写字母将用于“ x”,而大写字母将与“ X”一起使用。 这些仅适用于整数。
  • ‘e’, ‘E’, ‘f’, ‘F’ – used with floating point numbers for Exponent notation and Fixed-point notation respectively“ e”,“ E”,“ f”,“ F” –与浮点数一起使用,分别用于指数表示法和定点表示法

Let’s look at some examples of using format() function with numbers.

让我们看一些将format()函数与数字一起使用的示例。

# integers
print(format(10, '+'))
print(format(15, 'b'))print(format(15, 'x'))
print(format(15, 'X'))# float
print(format(.2, '%'))
print(format(10.5, 'e'))
print(format(10.5, 'e'))
print(format(10.5345678, 'f'))
print(format(10.5, 'F'))

Output:

输出:

+10
1111
f
F
20.000000%
1.050000e+01
1.050000e+01
10.534568
10.500000

自定义对象的Python format()函数 (Python format() function for Custom Object)

Let’s see how we can use format() function with custom object. We will create a class and define __format__() function for it. This function must return string otherwise we will get error.

让我们看看如何将format()函数与自定义对象一起使用。 我们将创建一个类并为其定义__format __()函数。 该函数必须返回字符串,否则我们将得到错误。

class Data:id = 0def __init__(self, i):self.id = idef __format__(self, format_spec):print('__format__ method called')if format_spec == 's':return "Data[id=%s]" % self.idif format_spec == 'i':return str(self.id)else:return 'invalid format spec'

Notice that I am formatting object based on the input format specification. If unrecognized format specs are provided, I am returning an error string. We can also throw an exception to be handled by the calling code.

请注意,我正在根据输入格式规范来格式化对象。 如果提供了无法识别的格式规范,我将返回错误字符串。 我们还可以抛出异常,以由调用代码处理。

d = Data(20)
print(format(d, 's'))
print(format(d, 'i'))
print(format(d, 'x'))

Output:

输出:

__format__ method called
Data[id=20]
__format__ method called
20
__format__ method called
invalid format spec
GitHub Repository.GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/22821/python-format-function

Python format()函数相关推荐

  1. Python format 函数- Python零基础入门教程

    目录 一.format 函数简介 1.format 函数不设置下标 2.format 函数设置下标 二.format 函数实战 三.猜你喜欢 零基础 Python 学习路线推荐 : Python 学习 ...

  2. Python .format()函数使用方法

    本文系统的介绍了Python中格式化输入方法format()函数的使用方法. 写下这篇博文的初衷是在学习的过程中发现许多博文对该方法的描述十分具体但还不够详尽,有互相补充的部分,许多书中的内容又受到版 ...

  3. python Format()函数的用法___实例详解(一)(全,例多)___各种格式化替换,format对齐打印

    python Format()函数的用法___实例详解(一)(全,例多) (格式化替换,关键字替换,列表字典替换,类格式化, 魔法函数格式化,对齐及填充格式化,format对齐打印) 本篇目录内容:

  4. python format函数实例_Python字符串格式化,format格式化函数详细使用

    Python接触比较多的是字符串,那么操作字符串也就多.Python 支持格式化字符串的输出 . 尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符的字符串中. 代码 ...

  5. Python format() 函数

    Python2.6 开始,新增了一种格式化字符串的函数 format() ,它增强了字符串格式化的功能. 基本语法是通过 {} 和 : 来代替以前的 % . format () 函数可以接受不限个参数 ...

  6. python format函数实例_python中强大的format函数实例详解

    python中format函数用于字符串的格式化 自python2.6开始,新增了一种格式化字符串的函数str.format(),此函数可以快速处理各种字符串. 语法 它通过{}和:来代替%. 请看下 ...

  7. python format函数换行_python format函数/print 函数详细讲解(19)

    文章首发微信公众号,微信搜索:猿说python 在python开发过程中,print函数和format函数使用场景特别多,下面分别详细讲解两个函数的用法. 一.print函数 print翻译为中文指打 ...

  8. Python format函数

    Python字符串的format函数 format()函数用来收集其后的位置参数和关键字段参数,并用他们的值填充字符串中的占位符.通常格式如下: '{pos or key : fill, align, ...

  9. python内置函数format的使用方法 python format函数怎么用

    1.基本语法 format 函数可以接受不限个参数,位置可以不按顺序. 如:"{1} {0} {1}".format("hello", "world& ...

  10. Python format函数——学习笔记

    format函数 格式化字段将会被 format() 中的参数替换 print("我叫{},今年{}!".format("拐鸽弟弟",22)) print(&q ...

最新文章

  1. 开源:Angularjs示例--Sonar中项目使用语言分布图
  2. 如何在windows系统上安装ubuntu双系统
  3. UA MATH567 高维统计I 概率不等式3 亚高斯性与亚高斯范数
  4. 蓝马linux命令连另一台电脑,配置使用别的电脑连接另一台电脑当中的虚拟机项目...
  5. 最详细的docker安装rocketMQ教程来了
  6. Too Many Segments (easy version) CodeForces - 1249D1(贪心+差分)
  7. C语言 break 和 continue - C语言零基础入门教程
  8. uni怎么使用原生html标签,uni-app如何完美解析富文本内容
  9. 基元线程同步构造之waithandle中 waitone使用
  10. mac中一一些常用的命令
  11. 房贷提前还款怎么还?
  12. 北京工商大学c语言复试试题,2016年北京工商大学计算机与信息工程学院C语言程序设计复试笔试仿真模拟题...
  13. ITIL4 服务管理的四个维度
  14. Java笔记——08.面向对象(中级)
  15. 互联网大厂薪资最全揭秘:阿里巴巴
  16. 咪咕MGV2000-KL 16G 晶晨S905L3 广东爱家TV 卡刷包
  17. 知识点总结 2022-8-15
  18. jQuery幸运大转盘
  19. 13个问题,评估开发团队优劣
  20. 天猫升级:用“大数据”做生意

热门文章

  1. Monkeyrunner脚本的录制与回放
  2. FreeMarker 基础语法教程
  3. [转载] Python---函数式编程(map()、filter()和reduce())总结
  4. Spring Boot 初体验(8)配置server信息
  5. [物理学与PDEs]第5章第3节 守恒定律, 应力张量
  6. 每天备份数据库中的表
  7. 怎样快速更新已安装的软件?
  8. 数据结构上机实践第四周项目2 - 建设“单链表”算法库
  9. 图像处理随笔——非极大值抑制
  10. 舵机任意角度程序_【舵机初动】基于Mind+ Ardunio入门教程10