1. 程式人生 > >Python中使用.format方法替代格式化操作符%

Python中使用.format方法替代格式化操作符%

Python中格式化字串的方式有:

    格式化操作符%,基本語法:%[轉換標記][寬度[.精確度]]轉換型別,其中轉換標記和轉換型別詳見《Python基礎教程第2版》3.3節,《改善Python程式的91個建議》建議28;

    .format方法,基本語法:[[填充符]對齊方式][符號][#][0][寬度][,][.精確度][轉換型別],其中填充符是除了“{}”外任意符號,對齊方式,符號,轉換型別詳見《91個建議》。

%常見用法:

    1.直接格式化字元或數值;

    >>>print "your score is %06.1f" % 9.5
    2.用元組格式化;

    >>>print "the %s of a circle with radius %f is %0.3f"  % (itemname,radius,math.pi*radius*2)
    3.用字典格式化;

    >>>itemdict = {'itemname':'circumference','radius':'3','value':math.pi*radius*2}

>>>print "the %(itemname)s of a circle with radius %(radius)f is %(value)0.3f" % itemdict

.format常見用法:

    1.使用符號;

>>>"The number {0:,} in hex is: {0:#x},the number {1} in oct is {1:#o}".format(4746,45)
    2.使用名稱;

>>>print "the max number is {max},the min number is {min},the average number is {average:0.3f}".format(max=189,min=12.6,average=23.5)
    3.通過屬性

>>>class Customer(object):

... def __init__(self,name,gender,phone):

... self.name = name

... self.gender = gender

... self.phone = phone

... def __str__(self):

... return 'Customer({self.name},{self.gender},{self.phone})'.format(self.self) #通過str函式返回結果

    4.格式化元組的具體項;

>>>point = (1,3)

>>>'X:{0[0]};Y:{0[1]}'.format(point)

參考書籍:

1.《Python基礎教程第2版》

2.《編寫高質量程式碼改善Python程式的91個建議》

相關推薦

Python使用.format方法替代格式化操作符%

Python中格式化字串的方式有:     格式化操作符%,基本語法:%[轉換標記][寬度[.精確度]]轉換型別,其中轉換標記和轉換型別詳見《Python基礎教程第2版》3.3節,《改善Python

pythonformat()方法格式化字串

format()是python2.6新增的一個格式化字串的方法,功能非常強大,有可能在未來完全替代%格式化方法,相比 % ,format()的優點有: 1 .格式化時不用關心資料型別的問題,forma

python 打印及格式化字符串的相關方法

aic 內容 fun 需要 ted selected con ... rep 原文 將值轉換為字符串 Python 有多種方式將任何值轉為字符串: 將它傳給 repr() 或 str() 函數. repr() 和 str() 的區別,看幾個例子: >>>

Python 字串-格式化-format()格式化操作符 : %

字串-格式化1.format()--方法接受位置引數和關鍵字引數,二者均傳遞到一個叫做replacement欄位。而replacement欄位在字串內由大括號 { } 表示。位置引數:name = '{0}80後,{1},{2}'.format('今晚','主持人','王自健

pythonstrip()方法學習筆記

bbb 方法學 python pytho ring strip strip() clas ng2 Python strip() 方法用於移除字符串頭尾指定的字符(默認為空格)。 當使用strip(‘xxx‘),只要字符串頭尾有"xxx"中的一個,就會去掉,而不是符合字符串‘

Python__init__()方法註意點

def c# bsp style get div 調用 pre 使用 此文轉自https://www.cnblogs.com/zyxstar2003/archive/2011/03/21/1989954.html 1、__init__並不相當於C#中的構造函數,執行它的時候

Python中用format函數格式化字符串的用法

常量 bar python2 可謂 jin strong was 對象 之前 Python中用format函數格式化字符串的用法 自python2.6開始,新增了一種格式化字符串的函數str.format(),可謂威力十足。那麽,他跟之前的%型格式化字符串相比,有什麽優越的

Python私有方法和私有屬性

Python 私有方法 私有屬性 1.私有方法和私有屬性私有方法只能在類內部被調用,不能被對象使用私有屬性只能在類內部使用,不能被對象使用 私有屬性只能在類內部使用,對象不能使用,但是,我們可以通過在類內部定義公有方法對私有屬性進行調用或修改,然後對象在調用這個公有方法使用。###私有屬性和私有方

Pythonsorted()方法的用法

OS 添加 -m bar AR python led list self Python中sorted()方法的用法 Python 字號<span pnt="" fc03"="" id="$_blog_subscribe" style="marg

python靜態方法、類方法、屬性方法區別

ref self 使用 lan com 通過 場景 UNC cme 在python中,靜態方法、類方法、屬性方法,剛接觸對於它們之間的區別確實讓人疑惑。 類方法(@classmethod) 是一個函數修飾符,表是該函數是一個類方法 類方法第一個參數是cls,而實例方法第

python魔術方法簡述

圖片 water pro 程序 基類 get ffffff http cbc 魔術方法:***實例化:new :實例化一個對象 方法很少使用,一般使用return super().))new(cls)基類ibject方法來創建實例並返回。 hash:返回一個整數,如

python linspace()方法

linspace(1,10) 在預設的情況下,linspace函式可以生成元素為50的等間隔數列。而其中的兩個引數分別是數列的開頭與結尾。 linspace(1,10,10) 如何寫入了第三個引數,可以指定數列元素的個數。 import numpy as np a = np.li

pythoninit()方法和new()方法的區別

new()理解: class A(object): def __init__(self,*args,**kwargs): print "init &&&& %s" % self.__class__ def __new__(

詳解pythonformat函式的強大功能

1、引數替換        format函式可以不限定引數個數,不限定引數位置。        一、不設定指定位置,按預設順序           &nb

Python方法定義及常用的實現方式

1. python類的屬性和方法檢視 class Person_1: mind = '有思想' belif = '有信仰' animal = '高階動物' def tt(): pass print(Person_1.__dict_

Python進階(十二)-淺談python方法

分享一下我的偶像大神的人工智慧教程!http://blog.csdn.net/jiangjunshow 也歡迎轉載我的文章,轉載請註明出處 https://blog.csdn.net/mm2zzyzzp Python進階(十二)-淺談python中的方法

python日期和時間格式化

本文例項總結了python中日期和時間格式化輸出的方法。分享給大家供大家參考。具體分析如下: python格式化日期時間的函式為datetime.datetime.strftime();由字串轉為日期型的函式為:datetime.datetime.strptime(),兩個函式都涉及日期時間的格

Pythoninit方法和del方法的使用

import time class Animal(object): def __init__(self,name): print("init 方法被呼叫") self.name = name def __del__(self): pri

pythonformat函數

{0} com print 表示 使用 分享圖片 bubuko alt div python中format函數用於字符串的格式化 通過關鍵字 1 print(‘{名字}今天{動作}‘.format(名字=‘陳某某‘,動作=‘拍視頻‘))#通過關鍵字 2 grade = {

Pythonsuper()方法的使用

如果在子類中也定義了構造器,既_init_()函式,那麼基類的構造器該如何呼叫呢? 方法一、明確指定  使用一個子類的例項去呼叫基類的構造器,在子類的構造器中明確的指明呼叫基類的構造器。 class  C(P): ...     def __ini