format內建函式

2022-05-01 16:00:15 字數 2748 閱讀 5403

1. 函式功能將乙個數值進行格式化顯示。

2. 如果引數format_spec未提供,則和呼叫str(value)效果相同,轉換成字串格式化。

>>> format(3.1415936)

'3.1415936

'>>> str(3.1415926)

'3.1415926

'

3. 對於不同的型別,引數format_spec可提供的值都不一樣

#

字串可以提供的引數,指定對齊方式,《是左對齊, >是右對齊,^是居中對齊

print(format('

test

', '

<20'))

print(format('

test

', '

>20'))

print(format('

test

', '

^20'))#

整形數值可以提供的引數有 'b' 'c' 'd' 'o' 'x' 'x' 'n' none

>>> format(3,'

b') #

轉換成二進位制'11

'>>> format(97,'

c') #

轉換unicode成字元'a

'>>> format(11,'

d') #

轉換成10進製'11

'>>> format(11,'

o') #

轉換成8進製'13

'>>> format(11,'

x') #

轉換成16進製制 小寫字母表示'b

'>>> format(11,'

x') #

轉換成16進製制 大寫字母表示'b

'>>> format(11,'

n') #

和d一樣'11

'>>> format(11) #

預設和d一樣'11

'#浮點數可以提供的引數有 'e' 'e' 'f' 'f' 'g' 'g' 'n' '%' none

>>> format(314159267,'

e') #

科學計數法,預設保留6位小數

'3.141593e+08

'>>> format(314159267,'

0.2e

') #

科學計數法,指定保留2位小數

'3.14e+08

'>>> format(314159267,'

0.2e

') #

科學計數法,指定保留2位小數,採用大寫e表示

'3.14e+08

'>>> format(314159267,'

f') #

小數點計數法,預設保留6位小數

'314159267.000000

'>>> format(3.14159267000,'

f') #

小數點計數法,預設保留6位小數

'3.141593

'>>> format(3.14159267000,'

0.8f

') #

小數點計數法,指定保留8位小數

'3.14159267

'>>> format(3.14159267000,'

0.10f

') #

小數點計數法,指定保留10位小數

'3.1415926700

'>>> format(3.14e+1000000,'

f') #

小數點計數法,無窮大轉換成大小字母(e後面的數值就是e的多少次冪)

'inf'#

g的格式化比較特殊,假設p為格式中指定的保留小數字數,先嘗試採用科學計數法格式化,得到冪指數exp,

如果-4<=exp>>> format(0.00003141566,'

.1g') #

p=1,exp=-5 ==》 -4<=exp'

3e-05

'>>> format(0.00003141566,'

.2g') #

p=1,exp=-5 ==》 -4<=exp'

3.1e-05

'>>> format(0.00003141566,'

.3g') #

p=1,exp=-5 ==》 -4<=exp'

3.14e-05

'>>> format(0.00003141566,'

.3g') #

p=1,exp=-5 ==》 -4<=exp'

3.14e-05

'>>> format(3.1415926777,'

.1g') #

p=1,exp=0 ==》 -4<=exp'3'

>>> format(3.1415926777,'

.2g') #

p=1,exp=0 ==》 -4<=exp'

3.1'

>>> format(3.1415926777,'

.3g') #

p=1,exp=0 ==》 -4<=exp'

3.14

'>>> format(0.00003141566,'

.1n') #

和g相同

'3e-05

'>>> format(0.00003141566,'

.3n') #

和g相同

'3.14e-05

'>>> format(0.00003141566) #

和g相同

'3.141566e-05

'

Matlab基本函式 format函式

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!1 format函式 控制輸出 顯示格式 2 用法說明 format 預設格式,同short。matlab中常用的顯示格式有 1 format short表示5位近似定點數 2 format long 15位近似定點數 3 format hex 十...

Format函式的用法

format函式的用法總結如下 函式宣告 function format const format string const args array of const string overload 函式功能 事實上format方法有兩個種形式,另外一種是三個引數的,主要區別在於它是執行緒安全的,但並...

format函式用法詳解

指定需要輸出內容的位置 通過位置進行輸出選擇 print format chuhao 20,laowang 指定輸出內容 print format chuhao 20,laowang 通過大括號的個數來判斷輸出的字串數 print format chuhao 20,laowang 通過關鍵字引數進行...