Python學習筆記:格式化輸出之f-string、format、%


一、%占位符

1.說明

# 符號代表意義
%s -- 字符串
%10s -- 指定長度 左填充
%-10s -- 指定長度 右填充

%f -- 浮點數
%.2f -- 保留2位小數點

%d -- 整數

2.實操

a = 'Name'
b = 'Hider'
c = 100
d = 1.80

print("My %s is %s." % (a, b))
# My Name is Hider.

print("My %s is %s. And my age is %d. My height is %f." % (a, b, c, d))
# My Name is Hider. And my age is 100. My height is 1.800000.

%f 默認精度是保留后6位,可通過 %.2f 設置。

print("My %s is %s. And my age is %d. My height is %.2f." % (a, b, c, d))
# My Name is Hider. And my age is 100. My height is 1.80.

字符串長度填充。

# 左填充
print('%10s' % ('Hider'))  #      Hider

# 右填充
print('%-10s' % ('Hider')) # Hider  

二、f-string格式化

f-string 直接使用變量名填充句子當中的內容。

Python 3.6 及以后版本支持 f-string 格式化輸出字符串。優先推薦!!!

a = 'Name'
b = 'Hider'
print(f'My {a} is {b}.')
# My Name is Hider.

print(f'計算結果為:{2*5 + 3*10}')
# 計算結果為:40

string_test = 'ABC'
print(f'It\'s {string_test.lower()}')
# It's abc

三、format關鍵字

1.格式化輸出

format 關鍵字用來格式化輸出字符串。不同入參情況:

  • 不指定位置
a = 'Name'
b = 'Hider'
c = 100
d = 1.80

print('My {} is {}.'.format(a,b))
# My Name is Hider.

位置默認開始從 0 計算,然后對應位置填入數據。

  • 指定位置
a = 'Name'
b = 'Hider'
c = 100
d = 1.80

print('My {0} is {1}. And my age is {2}.'.format(a,b,c))
# My Name is Hider. And my age is 100.

print('My {1} is {2}. And my age is {0}.'.format(a,b,c))
# My Hider is 100. And my age is Name.
  • 關鍵字配對
print('My {a} is {b}. And my age is {c}.'.format(a=10,b=20,c=30))
# My 10 is 20. And my age is 30.
  • 字典參數
dic = {'a':10, 'b':20, 'c':30}
print('My {a} is {b}. And my age is {c}.'.format(**dic))
# My 10 is 20. And my age is 30.

  • 列表參數
lis = ['a','b','c']
s = 'i like {} and {} and {}.'.format(*lis)
print(s)
# i like a and b and c.

2.精度

pi = 3.1415926535
print('{:.2f}'.format(pi)) # 3.14
print('{:+.3f}'.format(pi)) # +3.142
print('{:.2%}'.format(pi)) # 314.16%

3.千分位分隔符

主要用於貨幣數據的格式化輸出。

a = 1000000000
print('{:,}'.format(a)) # 1,000,000,000

# 添加貨幣符號
print('${:,}'.format(a)) # $1,000,000,000

參考鏈接:【Python】全方面解讀Python的格式化輸出

參考鏈接:萬字長文,史上最全Python字符串格式化講解


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM