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.pswp.cn/news/377824.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/377824.shtml
英文地址,請注明出處:http://en.pswp.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