Python format()函数

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 = 0

    def __init__(self, i):
        self.id = i

    def __format__(self, format_spec):
        print('__format__ method called')
        if format_spec == 's':
            return "Data[id=%s]" % self.id
        if 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值