Python 和format的用法

2022-04-29 11:03:11 字數 2370 閱讀 9219

#

八進位制oct %o

print('

%o' % 10) #12#

十進位制dec %dprint('

%d' % 1) #

10#

十六進製制hex %x

print('

%x' % 1) #

a

#

%f 預設保留6位小數 %.1f 保留1位小數

print('

%f,%.1f

' % (1.11,1.11)) #

1.110000,1.1

#%e 預設保留6位小數,用科學計算法 ,%.1保留1位小數

print('

%e,%.1e

' % (1.11,1.11)) #

1.110000e+00,1.1e+00

#%g 在保證六位有效數字的前提下,使用小數方式,否則使用科學計數法

print('

%g,%.1g

' % (1.1111111,1.1111)) #

1.11111,1

print('

%g,%.1g

' % (11111111.1,11111111)) #

1.11111e+07,1e+07

#

%s字串輸出

print('

%s' % '

hi')#hi#

%ns 右對齊,n位佔位符,不夠則補位

print('

%10s

' % '

hi,hi,hi

') #

hi,hi,hi

#%-ns 左對齊,n位佔位符,不夠則補位

print('

%-10s

' % '

hi,hi,hi

') #

hi,hi,hi

print('

%-10s

' % '

hi,hi,hi,hi,hi

') #

hi,hi,hi,hi,hi

#%.ns 擷取n個字串

print('

%.2s

' % '

hi,hi,hi

') #hi#

%n.ns 整數部分是佔位符,小數點是擷取n個字串

print('

%10.2s

' % '

hi,hi,hi

') #

hi

#

『{}』 最簡單格式

print('

{},{}

'.format('

hello

','world

')) #

hello,world

#位置編號

print('

,'.format('

hello

','world'))

print('

,,'.format('

hello

','world

')) #

位置編號,可以輸出多次 hello,world,hello

print('

,'.format('

hello

','world

')) #

world,world

#print('

,'.format(a='

hello

',b='

world

')) #

print('

'.format(0.12354)) #

百分比print('

'.format(123456789)) #

會計千位分隔符

print('

'.format(31.31412)) #

保留2位小數

#

list對映,格式是0[i]

l=list('

abcd')

print('

,,,'

.format(l))

#

dict ,格式是key引用

dict=

print('

name is ,age is

'.format(**dict)) #

name is tom,age is 20

python中format的用法 用住房來理解

學生黨在家沒事做寫的,就當練練文筆。format的格式化,我用生活中的住房子為例。print is a good format canglaoshi teacher out canglaoshi is a good teacherprint is a good format canglaoshi t...

Python裡format 格式化輸出的用法

最近在學習python,對format 函式的使用不是很清楚,搜尋了一些前輩的部落格獲得了一些經驗,加上自己摸索得出了一些新的想法 1.位置引數控制輸出 今天是乙個且的一天 format 溫暖 舒服 輸出 今天是乙個溫暖且舒服的一天 今天是乙個且的一天 format 溫暖 舒服 輸出 今天是乙個舒服...

python 格式輸出( 用法和format)

今天修改程式,比較糾結用哪個,搜資料整理一下。format 用法相對於基本格式 的用法,功能要強大很多。將字串當成模板,通過傳入的引數進行格式化,並且使用大括號 作為特殊字元代替 correct print the number is d 20 輸出 the number is 20 error p...