1. 程式人生 > >Python 字串輸出格式總結

Python 字串輸出格式總結

設定Python中字串輸出格式(或者說是認為設定的形式)有很多種方法,str()與repr()兩個內建函式是兩個內建的字串轉換函式,字串輸出格式控制中,有format()、轉義字元轉換等方法,下面一一介紹總結:

1、str()與repr()
str()與repr()兩個Python內建函式都是可以將任意實現__str__()和__repr__()方法的物件轉換為字串形式。其區別就是str()以更加適應人性化的觀測方式,而repr是直譯器可讀的形式。其在類中可通過__str__()與__repr__()兩個方法進行實現。如下程式碼:

s = 'Welcome to China'
print(str(s)+'\n'+repr(s))
輸出結果為:
Welcome to
China 'Welcome to China' s = 'Welcome to China\n' print(str(s) + repr(s)) 輸出結果為: Welcome to China 'Welcome to China\n' 從上面可以看出repr(s)將s全部字元輸出,str(s)將s以人為可視方式輸出,該轉義的會轉換

2、輸出字串對齊方式
python字串物件含有方法rjust(width[,fillchar]):右對齊、ljust(width[,fillchar]):左對齊、center(width[,fillchar]):中心對齊、zfill(width):對數字字串左補0對齊。上面的[]代表可選引數,width為輸出共佔有的字元數,fillchar為補全字元,預設為空格。下面實際程式碼:

s = "1234"
#右對齊
print(s.rjust(10))
print(s.rjust(10,'*'))
輸出結果:
      1234
******1234

#左對齊
print(s.ljust(10))
print(s.ljust(10,'*'))
輸出結果:
1234
1234******

#中心對齊
print(s.center(10))
print(s.center(10,'*'))
輸出結果:
   1234
***1234***

#zfill
print(s.zfill(3))
print(s.zfill(10))
輸出結果為:
1234
0000001234

3、使用str.format()格式化輸出
Python中字串物件含有format方法,可以進行特定的格式化輸出,其一般的格式為”…{0}…{1}…{2}…{n}”.format(任意物件,任意物件,任意物件…任意物件),會將{0}、{1}…依次轉換為format裡面的相應物件,在Python3中{}裡面可以不加標號,但是數量應該對於,format裡面的引數可以多於或者等於{}的個數。下面以程式碼分別解釋一些常用的形式:

N = {"Kangkang":"China","Maria":"America"}
name = "Maria"
country = "China"
L = ["Kangkang", "Maria"]

s1 = "{0},Welcome to {1}".format(name,country)

s2 = "{1},Welcome to {0}".format(country,name)

s2 = "{},Welcome to {}".format(name,country)

s3 = "{0[Kangkang]} and {0[Maria]} are two countries".format(N)

s4 = "{name},Weclome to {country},I'm so 
{feeling}".format(**locals(),feeling="excited")

s5 = "{Kangkang} and {Maria}".format(**N)

s6 = "{0[0]} and {0[1]} are good friends".format(L)

s7 = "{name} come frome {country}".format(**locals())

print("{s1}\n{s2}\n{s3}\n{s4}\n{s5}\n{s6}\n{s7}\n".format(**locals()))

#輸出結果
Maria,Welcome to China
Maria,Welcome to China
China and America are two countries
Maria,Weclome to China,I'm so excited
China and America
Kangkang and Maria are good friends
Maria come frome China

4、使用轉義字元格式化輸出。基本上程式語言都支援轉義字元格式化輸出。下面給出python支援的轉義字元表格。
這裡寫圖片描述根據想要轉義的字元就可格式化輸出,例如:

print("name\t\tcountry\t")
print("%s\t\t%s\t"%("Kangkang", "China"))
print("%s\t\t%s\t"%("Maria", "America"))