博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python字符串格式:%vs.format
阅读量:2528 次
发布时间:2019-05-11

本文共 3272 字,大约阅读时间需要 10 分钟。

Often the string formatters in python are referred to as old style and new style. The old-style is '%' and .format is known as the new style.

python中的字符串格式化程序通常被称为旧样式和新样式。 旧样式为'%' ,. format被称为新样式。

Simple positional formatting is the most common use-case. This formatting is used if the order of the arguments is not likely to change and there are very few elements to be concatenated.

简单的位置格式是最常见的用例。 如果参数的顺序不太可能更改并且要连接的元素很少,则使用这种格式。

Example:

例:

# string concatenation using %print('%s %s'%('one','two'))# string concatenation using .formatprint('{} {}'.format('one','two'))

Output

输出量

one twoone two

With the new style formatting, it is possible to give placeholders an explicit positional index. This allows for rearranging the order of display without changing the arguments. This feature is not available in the old style.

使用新的样式格式,可以为占位符提供显式的位置索引。 这样可以在不更改参数的情况下重新排列显示顺序。 旧功能不提供此功能。

Example:

例:

print('{0} {1}'.format('one','two'))print('{1} {0}'.format('one','two'))

Output

输出量

one twotwo one

填充和对齐字符串 (Padding and aligning strings)

By default, values are formatted to take up only as many characters as needed to represent the content. It is, however, possible to define that a value should be padded to a specific length.

默认情况下,将值格式化为仅占用表示内容所需的尽可能多的字符。 但是,可以定义应将值填充为特定长度。

Example:

例:

print('%10s'%('test'))print('{:>10}'.format('test'))

Output

输出量

test      test

截断长弦 (Truncating long strings)

It is also possible to truncate overly long values to a specific number of characters. The number behind a . (dot) in the format specifies the precision of the output. For strings that means that the output is truncated to the specified length. In our example, this would be 3 characters.

也可以将过长的值截断为特定数量的字符。 后面的数字。 格式中的(点)指定输出的精度。 对于字符串,这意味着输出将被截断为指定的长度。 在我们的示例中,这将是3个字符。

Example:

例:

print('%.3s'%('includehelp',))print('{:.3}'.format('includehelp'))

Output

输出量

incinc

号码 (Numbers)

Example:

例:

print('%d' %(10000))print('{:d}' .format(10000))

Output

输出量

1000010000

参数化格式 (Parametrized formats)

New style formatting allows all of the components of the format to be specified dynamically using parametrization. Parametrized formats are nested expressions in braces that can appear anywhere in the parent format after the colon. Old style formatting also supports some parametrization but is much more limited. Namely, it only allows parametrization of the width and precision of the output.

新样式格式允许使用参数化动态指定格式的所有组件。 参数化格式是括号中的嵌套表达式,可以在冒号之后的父格式中的任何位置出现。 旧样式的格式也支持某些参数化,但局限性更大。 即,它仅允许对输出的宽度和精度进行参数化。

Example:

例:

from datetime import datetimedt = datetime(2019, 12, 19, 4, 5)print('{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M'))

Output

输出量

2019-12-19 04:05

自定义对象 (Custom Objects)

The datetime example works through the use of the __format__() magic method. However, one defines custom format handling in own objects by overriding this method. This gives complete control over the format syntax used.

datetime示例通过使用__format __()魔术方法来工作。 但是,通过覆盖此方法,可以在自己的对象中定义自定义格式处理。 这样可以完全控制所使用的格式语法。

Example:

例:

class Type2000(object):  def __format__(self, format):    if (format == 'test-format'):      return "This is format example for include help."    return 'Type 2000'print('{:test-format}'.format(Type2000()))

Output

输出量

This is format example for include help.

翻译自:

转载地址:http://emxzd.baihongyu.com/

你可能感兴趣的文章
mysql中间件研究(tddl atlas cobar sharding-jdbc)
查看>>
Cast-128 加密算法和 MyPassWord 的破解
查看>>
4.28下午 听力611
查看>>
ActiveMQ学习笔记(1)----初识ActiveMQ
查看>>
Java与算法之(2) - 快速排序
查看>>
Windows之IOCP
查看>>
机器学习降维之主成分分析
查看>>
CTP2交易所成交回报
查看>>
WebSocket & websockets
查看>>
《机器学习实战》学习笔记第二章 —— K-近邻算法
查看>>
uni-app 引入本地iconfont的正确姿势以及阿里图标引入
查看>>
DSB
查看>>
Java中的阻塞队列
查看>>
前端软件sublime的一些常用快捷键
查看>>
openssl 升级
查看>>
2017.10.30 天晴 昨天十公里没减肥
查看>>
Git 打标签(分布式版本控制系统)
查看>>
ASP.NET MVC:通过 FileResult 向 浏览器 发送文件
查看>>
CVE-2010-2883Adobe Reader和Acrobat CoolType.dll栈缓冲区溢出漏洞分析
查看>>
使用正确的姿势跨域
查看>>