Python之格式化字串format和Math庫

2021-10-05 09:41:14 字數 1879 閱讀 3372

import math

print

(math.pi)

print

(math.sin(math.pi/4)

)

輸出:

3.141592653589793

0.7071067811865476

5

2print

輸出結果:

5

210

但是不明白上面的數字的意思,可以輸出字串來實現:

print

("蘋果的**:{} 蘋果的重量{} 總的**{}"

.format

)

輸出結果:

蘋果的**:5 蘋果的重量2 總的**10
通過{}來實現字串的格式化

a=

10b=

20print

("交換前:a={} b={}"

.format

(a,b)

)a,b=b,a

print

("交換後:a={} b={}"

.format

(a,b)

)

交換前:a=

10 b=

20交換後:a=

20 b=

10

print

("保留小數點後6位:{}"

.format

(round

(math.pi,10)

))

保留小數點後6位:3.1415926536
#乘方

print

(math.

pow(3,

9))print(3

**9)#向下取整

print

(math.floor(

3.1415926))

#向上取整

print

(math.ceil(

3.1415926))

#角度裝弧度

print

(math.radians(90)

)

19683.0

1968334

1.5707963267948966

#取最小值

print

("這組數中的最小值:{}"

.format

(min(10

,23,1

,-1)

))#取最小大值

print

("這組數中的最大值:{}"

.format

(max(10

,23,1

,-1)

))#求商和餘數

print

("10÷3的商和餘數分別是:{}"

.format

(divmod(10

,3))

)

這組數中的最小值:-1

這組數中的最大值:

2310÷3的商和餘數分別是:(3,

1)

print

(true

andtrue

)print

(true

andfalse

)print

(not

true

)

true

false

false

Python之字串格式化

有時候在實際開發當中,需要執行原生sql語句或者想列印某些帶變數引數的字串,那麼就需要對字串進行格式化處理!字串格式化的種類 1 加法拼接 name thomas data my name is name data my name is thomas 2 格式符方式 name thomas heig...

Python 字串格式化

字串格式化 s 格式化為字串 format hello,s.s enough for ya?values world hot print format values hello,world.hot enough for ya?f 格式化為實數 浮點數 format pi with three dec...

python字串格式化

字串的格式化 在python中也有類似於c中的printf 的格式輸出標記。在python中格式化輸出字串使用的是 運算子,通用的形式為 其中,左邊部分的 格式標記字串 可以完全和c中的一致。右邊的 值組 如果有兩個及以上的值則需要用小括號括起來,中間用短號隔開。重點來看左邊的部分。左邊部分的最簡單...