Python字符串格式:%vs.format

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 .format
print('{} {}'.format('one','two'))

Output

输出量

one two
one 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 two
two 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

输出量

inc
inc

号码 (Numbers)

Example:

例:

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

Output

输出量

10000
10000

参数化格式 (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 datetime
dt = 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.

翻译自: https://www.includehelp.com/python/string-formatting-vs-format.aspx

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/377824.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【C++grammar】代理构造、不可变对象、静态成员

目录1、Delegation Constructor(代理构造)1. What is delegating constructor? (什么是代理构造/委托构造)2. Avoiding recursive calls of target constructors (避免递归调用目标ctor)3. 委托构造的好处2、不可变对象和类1、如何让类成为“不可变类”…

paip.最新的c++ qt5.1.1环境搭建跟hello world

paip.最新的c qt5.1.1环境搭建跟hello world 作者Attilax , EMAIL:1466519819qq.com 来源:attilax的专栏 地址:http://blog.csdn.net/attilax 有一段时间没接触c了...今天下载新的qt下来研究一番.. qt的环境搭建有eclipseqtdtmingwqtl…

RFID模块+WIFI模块+振动传感器+有源蜂鸣器+舵机+Arduino UNO R3所构成的门禁系统模块

该系统模块主要由RFID模块WIFI模块振动传感器有源蜂鸣器舵机Arduino UNO R3组成的门禁系统模块。这里使用舵机充当门锁,用户可以刷卡开门,也可以通过APP控制舵机状态达到开门的效果。若有不法分子想要强行进入室内,对门进行撞击或者人为的破坏…

PushManager

http://suchandalex.googlecode.com/svn/trunk/beOui/beWe/client/Classes/PushNotificationManager.m转载于:https://www.cnblogs.com/vincent-lu/archive/2012/01/18/2325740.html

krsort_PHP krsort()函数与示例

krsortPHP krsort()函数 (PHP krsort() function) krsort() function is used to sort an associative array in descending order based on the keys, as we know that an associative array contains keys and values, this method sorts an array according to the keys. kr…

ESP12E Shield+Arduino UNO R3开发板+DHT11温湿度模块+双色LED灯+有源蜂鸣器+光敏电阻模块+I2CLCD1602液晶显示器所构成的室内检测系统

室内检测系统由ESP12E ShieldArduino UNO R3开发板DHT11温湿度模块双色LED灯有源蜂鸣器光敏电阻模块I2CLCD1602液晶显示器所构成。DHT11温湿度模块获取室内温湿度数据通过I2CLCD1602液晶显示器进行显示,另一方面通过ESP12E Shield将数据上传至云平台。光敏电阻进行捕…

输入输出函数:

一、printf函数:     printf("Hello World!\n");     printf("My age is %d\n",26);     int age 17;     printf("My age is %d\n",age);  %d 或 %i: 带符号 十进制整数。   %o:不带符号 八进制整数。   %x:…

leetcode 202. 快乐数 思考分析(哈希集合与双指针解)

1、题目 编写一个算法来判断一个数 n 是不是快乐数。 「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1&am…

五、线性回归和多项式回归实现

官网API 一、线性回归 针对的是损失函数loss faction Ⅰ、Lasso Regression 采用L1正则,会使得w值整体偏小;w会变小从而达到降维的目的 import numpy as np from sklearn.linear_model import Lasso from sklearn.linear_model import SGDRegresso…

JavaScript中的地图与对象

JavaScript对象与地图 (JavaScript Objects vs Maps) Objects are super popular in JavaScript so its not a term you are hearing for the first time even if youre a novice JS developer. Objects, in general, are a very common data structure that is used very ofte…

深发展银行编码器(解剖)

电池拆下来,再装上,还能继续用下,不会被重置 转载于:https://www.cnblogs.com/ahuo/archive/2012/01/25/2329485.html

关于$.getJson

这是一个Ajax函数的缩写,这相当于: 123456$.ajax({dataType: "json",url: url,data: data,success: success});数据会被附加到一个查询字符串的URL中,发送到服务器。如果该值的data参数是一个普通的对象,它会转换为一个字符串并使用…

leetcode 1. 两数之和 思考分析

1、题目 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。 2、思考分析 双for循环的时间复杂度…

六、逻辑回归

一、何为逻辑回归 逻辑回归可以简单理解为是基于多元线性回归的一种缩放。 多元线性回归y的取值范围在(-∞,∞),数据集中的x是准确的一个数值。 用这样的一个数据集代入线性回归算法当中会得到一个模型。 这个模型所具备的功能就是当有人给这个模型一个…

C# 调用Windows API实现两个进程间的通信

使用Windows API实现两个进程间(含窗体)的通信http://blog.csdn.net/huangxinfeng/article/details/5513608 从C#下使用WM_COPYDATA传输数据说到Marshal的应用http://www.cnblogs.com/jiangyh-is-me/archive/2006/06/05/417381.html 问题解决&#xff1a…

如何在Golang中返回错误?

In Golang, we return errors explicitly using the return statement. This contrasts with the exceptions used in languages like java, python. The approach in Golang to makes it easy to see which function returns an error? 在Golang中,我们使用return…

leetcode 383. 赎金信 思考分析

题目 给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串 ransom 能不能由第二个字符串 magazines 里面的字符构成。如果可以构成,返回 true ;否则返回 false。 (题目说明:为了不暴露赎金信字迹&#x…

Numpy(科学计算库)---讲解

本内容来自《跟着迪哥学Python数据分析与机器学习实战》,该篇博客将其内容进行了整理,加上了自己的理解,所做小笔记。若有侵权,联系立删。 迪哥说以下的许多函数方法都不用死记硬背,多查API多看文档,确实&a…

仿安居客好租网房产源码

网站设计简约,大方,清爽开发技术:ASP.NET3.5,SQL2005,VS2008功能简介1、小区,二手房,租房小区发布,编辑,修改功能,图片批量上传2、支持积分,发布房源、发布论坛帖子可获得…

Eclipse中classpath和deploy assembly的文件位置

classpath的配置信息存储在工程根目录下的.classpath文件 deploy assembly配置信息存储在工程目录下的.settings\org.eclipse.wst.common.component文件中转载于:https://www.cnblogs.com/jubincn/p/3381087.html