日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 格式化输出%和format

發布時間:2025/3/15 python 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 格式化输出%和format 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1 %用法

1.1整數的輸出

%o —— oct 八進制
%d —— dec 十進制
%x —— hex 十六進制

print('%o' % 20) #24 print('%d' % 20) #20 print('%x' % 20) #14

1.2浮點數輸出

%f ——默認保留小數點后面六位有效數字
  %.3f,保留3位小數位
%e ——默認保留小數點后面六位有效數字,指數形式輸出
  %.3e,保留3位小數位,使用科學計數法
%g ——在保證六位有效數字的前提下,使用小數方式,否則使用科學計數法
  %.3g,保留3位有效數字,使用小數或科學計數法

1.3round四舍五入

round(number[, ndigits])
參數:
number - 這是一個數字表達式。
ndigits - 表示從小數點到最后四舍五入的位數。默認值為0。
返回值
該方法返回x的小數點舍入為n位數后的值。

print(round(1.1125)) #1 print(round(1.1135,3)) #1.113 print(round(1.1125,3)) #1.113

1.4字符串輸出

%s
%10s——右對齊,占位符10位
%-10s——左對齊,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取兩位字符串

print('%s' % 'hello world') print('%s' % 1) print('%20s' % 'hello world') print('%-20s' % 'hello world') print('%.2s' % 'hello world') print('%10.2s' % 'hello world') print('%-10.2s' % 'hello world')

輸出結果:

print(’%s’ % ‘hello world’)
print(’%s’ % 1)
print(’%20s’ % ‘hello world’)
print(’%-20s’ % ‘hello world’)
print(’%.2s’ % ‘hello world’)
print(’%10.2s’ % ‘hello world’)
print(’%-10.2s’ % ‘hello world’)

常見格式:

常見轉義字符:

2 format用法

format()功能更強大,該函數把字符串當成一個模板,通過傳入的參數進行格式化,并且使用大括號‘{}’作為特殊字符代替‘%’

2.1位置匹配

(1)不帶編號,即“{}”

(2)帶數字編號,可調換順序,即“{1}”、“{2}”

(3)帶關鍵字,即“{a}”、“{tom}”

print('{} {}'.format('hello','world')) print('{0} {1}'.format('hello', 'world')) print('{0} {1} {0}'.format('hello','world')) print('{1} {1} {0}'.format('hello','world')) print('{a} {tom} {a}'.format(tom='hello',a='world'))

輸出結果

hello world
hello world
hello world hello
world world hello
world hello world

print( '{0}, {1}, {2}'.format('a', 'b', 'c')) print('{}, {}, {}'.format('a', 'b', 'c')) print( '{2}, {1}, {0}'.format('a', 'b', 'c')) print('{2}, {1}, {0}'.format(*'abc')) # 可打亂順序 print('{0}{1}{0}'.format('abra', 'cad')) # 可重復

輸出結果:

a, b, c
a, b, c
c, b, a
c, b, a
abracadabra

import datetime d=datetime.datetime(2010,7,4,12,15,34) print('{:%Y-%m-%d %H:%M:%S}'.format(d))

輸出結果:

2010-07-04 12:15:34

2.2左中右對齊及位數補全

(1)< (默認)左對齊、> 右對齊、^ 中間對齊、= (只用于數字)在小數點后進行補齊

(2)取位數“{:4s}”、"{:.2f}"等

points=19 total=22 print('Correct answers: {:.2%}'.format(points/total)) print('{} is {:.2f}'.format(1.123,1.123)) print('{0} is {0:>10.2f}'.format(1.123)) print('{:+f}; {:+f}'.format(3.14, -3.14)) # 總是顯示符號 print('{:,}'.format(1234567890))

輸出結果:

Correct answers: 86.36%
1.123 is 1.12
1.123 is 1.12
+3.140000; -3.140000
1,234,567,890

總結

以上是生活随笔為你收集整理的python 格式化输出%和format的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。