在寫代碼時,我們會經常與字符串打交道,Python中控制字符串格式通常有三種形式,分別是使用str%,str.format(),f-str,用法都差不多,但又有一些細微之差。
一起來看看吧~~~
一、%用法
1、字符串輸出
>>>print('hi! %s!'%('Echohye')) # 如果只有一個數,%后面可以不加括號,如print('hi! %s!'%'Echohye'),下同
hi! Echohye!
>>> name = 'Echohye'
>>> print('hi! %s'%(name)
hi! Echohye
>>> id = '123'
>>> print('%s的id是%s'%(name,id))
Echohye的id是123
2、整數輸出
b、d、o、x 分別是二進制、十進制、八進制、十六進制。
>>> print('今年%d歲了'%(20))
今年20歲了
3、浮點數輸出
%f ——保留小數點后面六位有效數字
%.2f,保留2位小數
>>> print('%f'%1.2345)
1.234500
>>> print('%.2f'%1.2345)
1.23
%e ——保留小數點后面六位有效數字,指數形式輸出
%.2e,保留2位小數位,使用科學計數法
>>> print('%e'%1.11111)
1.111110e+00
>>> print('%.2e'%1.11111)
1.11e+00
%g ——在保證六位有效數字的前提下,使用小數方式,否則使用科學計數法
%.2g,保留2位有效數字,使用小數或科學計數法
>>> print('%g'%1.2345678)
1.23457
>>> print('%.2g'%1.2345678)
1.2
4、占位符寬度輸出
%20s——右對齊,占位符10位
%-20s——左對齊,占位符10位
%.3s——截取3位字符
%20.3s——20位占位符,截取3位字符
%-10s%10s——左10位占位符,右10位占位符
小結:小數點前是正數,則右對齊;小數點前是負數,則左對齊;小數點后面是多少則截取多少位
格式符
格式符為真實值預留位置,並控制顯示的格式。格式符可以包含有一個類型碼,用以控制顯示的類型,如下:
%s 字符串 (采用str()的顯示)
%r 字符串 (采用repr()的顯示)
%c 單個字符
%b 二進制整數
%d 十進制整數
%i 十進制整數
%o 八進制整數
%x 十六進制整數
%e 指數 (基底寫為e)
%E 指數 (基底寫為E)
%f 浮點數
%F 浮點數,與上相同
%g 指數(e)或浮點數 (根據顯示長度)
%G 指數(E)或浮點數 (根據顯示長度)
>>> print('%20s'%('hi! Echohye'))
hi! Echohye
>>> print('%-20s'%('hi! Echohye'))
hi! Echohye
>>> print('%.3s'%('hi! Echohye'))
hi!
>>> print('%20.3s'%('hi! Echohye'))
hi!
>>> print('%-10s%10s'%('hi! ','Echohye'))
hi! Echohye
另外注意下面這種情況
>>> print('%5d'%3)
3
>>> print('%05d'%3)
00003
>>> print('%05s'%'3')
3
二、str.format()用法
官方文檔介紹:
Python2.6 開始,新增了一種格式化字符串的函數 str.format(),它增強了字符串格式化的功能。
基本語法是通過 {} 和 : 來代替以前的 % 。
format 函數可以接受不限個參數,位置可以不按順序。
下面我們一起研究看看吧
1、字符串輸出
>>>"{} {}!".format("hello", "Echohye") # 不設置指定位置,按默認順序
'hello Echohye!'
>>> "{0} {1}!".format("hello", "Echohye") # 設置指定位置
'hello Echohye!'
>>> "{1} {0}!".format("hello", "world") # 設置指定位置
'Echohye hello!'
設置帶參數:
# 通過字典設置參數
site = {"name": "Echohye", "wxNum": "Echo_hyee"}
print("名字:{name}, 微信號:{wxNum}".format(**site)) #**不能落下
# 通過列表索引設置參數
list = ['Echohye', 'Echo_hyee']
print("名字:{0[0]}, wxNum:{0[1]}".format(list)) #“0”不能落下
#那下面這樣子呢
>>> list = [['Echohye', 'Echo_hyee'],['小二', '12345']]
>>> print("名字:{0[0]}, wxNum:{0[1]}".format(list))
名字:['Echohye', 'Echo_hyee'], wxNum:['小二', '12345']
>>> print("名字:{0[1][0]}, wxNum:{0[1][1]}".format(list))
名字:小二, wxNum:12345
>>> print("名字:{0[0]}, wxNum:{0[1]}".format(list[0]))
名字:Echohye, wxNum:Echo_hyee
我只能說靈活運用哈
2、整數輸出
>>> print('{}'.format(1314))
1314
>>>print('{:.0f}'.format(1314.22)
1314
#這里不過多介紹了,個人感覺用法跟前面字符串輸出的差不多
3、浮點數輸出
# 保留小數后兩位
>>>print('{:.2f}'.format(3.1415926))
3.14
# 帶符號保留小數后兩位,+ 表示在正數前顯示 +,在負數前顯示 -
>>>print('{:+.2f}'.format(3.1415926))
+3.14
>>> print('{:+.2f}'.format(-3.1415926))
-3.14
# 不帶小數
>>>print('{:.0f}'.format(3.1415926)) # “0”不能省
3
4、占位符寬度輸出
# 空格補x,填充左邊,寬度為10
>>>print('{:x>10s}'.format('happy'))
xxxxxhappy
# 空格補x,填充右邊,寬度為10
>>>print('{:x<10s}'.format('happy'))
happyxxxxx
# 空格補x,填充兩邊,寬度為10
>>> print('{:x^10s}'.format('happy'))
xxhappyxxx # 如果占位符數是奇數,則右邊多於左邊
# 說明:x只能是指定一個字符,不可以多位,可以是任何字符,默認為空格
>>> print('{:>10s}'.format('happy'))
happy
>>> print('{:&>10s}'.format('happy'))
&&&&&happy
>>> print('{:`>10s}'.format('happy'))
`````happy
>>> print('{:.>10s}'.format('happy'))
.....happy
>>> print('{:/>10s}'.format('happy'))
/////happy
>>> print('{:a>10s}'.format('happy'))
aaaaahappy
>>> print('{:2>10s}'.format('happy'))
22222happy
5、其它格式
# 以逗號分隔的數字格式
>>> print('{:,}'.format(999999999))
999,999,999
# 百分比格式
>>> print('{:%}'.format(0.99999)) # 默認仍是六位小數
99.999000%
>>> print('{:.2%}'.format(0.99999))
100.00%
>>> print('{:.2%}'.format(0.9999))
99.99%
# 指數記法
>>> print('{:.0e}'.format(1000000))
1e+06
>>> print('{:.2e}'.format(1000000))
1.00e+06
>>> print('{:.2e}'.format(0.1000000))
1.00e-01
>>> print('{:.2e}'.format(0.000001))
1.00e-06
注:本處參考'菜鳥教程'
三、f-str用法
f-str的用法,其實跟str.format()的用法差不多,不過我跟喜歡用f-str,因為它更加簡潔、方便、高效。
1、字符串輸出
# 字符串輸入
>>> print(f"my name is {'Echohye'},nice to meet you!") # 這里得注意""和''的嵌套了
my name is Echohye,nice to meet you!
# 參數代入
>>> name = 'Echohye'
>>> print(f'my name is {name},nice to meet you!')
my name is Echohye,nice to meet you!
# 字符串截取
>>> name = 'Echohye'
>>> print(f"my name is {'Echohye':.3s},nice to meet you!")
my name is Ech,nice to meet you!
>>> print(f"my name is {name:.3s},nice to meet you!")
my name is Ech,nice to meet you!
# 有沒有覺得很方便快捷?haha,當然,這個Python2是不支持的喲~
2、整數輸出
>>> print(f'{1314}')
1314
>>> num = 1314
>>> print(f'{num}')
1314
3、浮點數輸出
...
4、占位符寬度輸出
...
用法跟str.format()的基本一樣,如果想繼續挖掘就參考前面的哈,我就不過多贅述了。目前我覺得二者區別就是把str.format()里()括號的內容放到了f'{:}'的:前面。當然,不一樣的地方可能也有,只是我還未遇到,靠大家一起來探索啦
四、討論一下print()函數
print() 方法用於打印輸出,是python中最常見的一個函數。
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
下面是print()的參數介紹
>>> help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
參數的具體含義如下:
value --表示輸出的對象。輸出多個對象時,需要用 , (逗號)分隔。
可選關鍵字參數:
file -- 要寫入的文件對象。
sep -- 用來間隔多個對象。
end -- 用來設定以什么結尾。默認值是換行符 \n,可以換成其他字符。
flush -- 輸出是否被緩存通常決定於 file,但如果 flush 關鍵字參數為 True,流會被強制刷新。
例子介紹:
value參數
>>> print('Echo','hye')
Echo hye
>>> print('Echo''hye')
Echohye
>>> print(1300,'+',14,'=',1300+14) #這個不錯,亂套也是行的haha
1300 + 14 = 1314
# 第二個其實還有個用處,比如你碼了一行很長的代碼,電腦屏幕都不夠顯示,我們這是就可以用print("""")打斷,但其實還是連着一起的。
>>> print('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa''cccccccccccccccccccccc')
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacccccccccccccccccccccc
# 我其實想在中間按個回車的,可IDLE Shell不能直接回車~~~但我們在py文件里面下還是可以的^_^
file參數
(略...)
sep參數
>>> print('Echo','hye',sep='?')
Echo?hye
# 試下把字符串間的逗號去掉,就不行了
>>> print('Echo''hye',sep='?')
Echohye
>>> print('Echo','hye',sep=' ~我裂開了~ ')
Echo ~我裂開了~ hye
>>> print('Echo','hye',sep='\n')
Echo
hye
>>> print('Echo','hye',sep='\t')
Echo hye
>>> print('Echo','hye',sep='\n\t')
Echo
hye
# 小結:sep=''里的字符,就是替換掉逗號的,而且不局限於一個字符,可以是一個字符串,也可以是轉義字符,專業字符還能組隊出場 ->(ΩДΩ)震驚~~~
# 是我孤陋寡聞了o(╥﹏╥)o
end參數
猜想:前面的sep參數是作用在中間的逗號,end參數是作用在結尾,而默認的是'\n',如果設其它參數,也就相當於替換掉'\n',那用法應該也是一致的。下面實踐看看
>>> print('Echo','hye',end='\nhere')
Echo hye
here
>>> print('Echo','hye',end='\there')
Echo hye here
>>> print('Echo','hye',end='\n\there')
Echo hye
here
# 實踐出真知,確實如此,end參數的用法跟sep參數的用法基本一樣
flush參數
# 在PyCharm里執行
import time
print("Loading", end="")
for i in range(10):
print(".", end='', flush=True)
time.sleep(0.5)
print()
print("Loading", end="")
for i in range(10):
print(".", end='', flush=False)
time.sleep(0.5)
#結果
Loading..........
Loading..........
我沒看出來有什么區別,可能用處不是在這,只是我還沒發現 &umum~
print()函數用法就介紹到這里咯,有興趣的小伙伴可以繼續深入了解哈~
注:終於結束了,淚奔~