iT邦幫忙

2023 iThome 鐵人賽

DAY 7
0
Software Development

跟著 OXXO 一起學 Python系列 第 13

( Day 7.2 ) Python 文字與字串 ( 格式化 )

  • 分享至 

  • xImage
  •  

在 Python 裡,除了可以使用基本功能串接字串,也可以針對不同的格式,將資料插入字串當中,由於 Python 版本的不同,這篇教學會介紹三種格式化字串的方法,透過字串的格式化,也可以輕鬆做出數字「補零」的效果。

原文參考:文字與字串 ( 格式化 )

本篇使用的 Python 版本為 3.7.12,所有範例可使用 Google Colab 實作,不用安裝任何軟體 ( 參考:使用 Google Colab )

%

「%」的字串格式化是「舊式」的格式化方法,適用於 Python 2 和 3 的版本,操作方式為「格式化字串 % 資料」,輸出結果會將資料插入格式化字串的位置。

格式化字串 轉換型態
%s 字串
%d 十進制整數
%x 十六進制整數
%o 八進制整數
%b 二進制整數
%f 十進制浮點數
%e 指數浮點數
%g 十進制或指數浮點數
%% 常值 %

下面的例子,印出 a 的內容時,會將內容的 %s 替換成 % 後方的字串,%d 會將浮點數的小數點無條件捨去,%f 則會將整數轉換成浮點數。( 如果用 %s 顯示數字,數字的型態會被轉換成文字 )

a = 'Hello world, I am %s!!'
b = 'there are %d dollars'
c = 'there are %f dollars'
print(a % 'oxxo')  # Hello world, I am oxxo!!
print(a % 'xoox')  # Hello world, I am xoox!!
print(b % 2.5)     # there are 2 dollars ( 小數點被無條件捨去 )
print(c % 2)       # there are 2.000000 dollars ( 整數轉換成浮點數 )

格式化字串的 % 和形態代號間,可以加入其他數值,來指定最小寬度、最大字元、對齊與精確度:

格式化數值 說明
不加東西、+ 靠右對齊
- 靠左對齊
數字 最小寬度 ( 如果字串超過最小寬度,以字串的寬度為主 )
數字.數字 最小寬度.最大字元數,如果後方是 f (%f),第二個數字表示小數點位數

下面的例子可以看到 %12s 會在 hello 前方加上七個空格 ( 7 + hello 總共 12 個字元 ),%.3s 會讓 hello 只剩下 hel ( 3 個字元 ),%.3f 會讓 123.456789 只留下小數點三位。

print('%s world' % 'hello')      # hello world
print('%12s world' % 'hello')    #        hello world
print('%+12s world' % 'hello')   #        hello world
print('%-12s world' % 'hello')   # hello        world
print('%.3s world' % 'hello')    # hel world
print('%12.3s world' % 'hello')  #          hel world

print('%.3f world' % 123.456789) # 123.457 world

如果有多個數值需要格式化,可以在 % 後方用小括號包住對應的參數,參數的數量和順序必須和前方的格式化字元相同

a = '%s world, ther are %f dollars!'
b = a % ('hello', 2.5)
print(b)   # hello world, ther are 2.500000 dollars!

.format

「{}」和「foramt()」是 Python 3 所使用的「新式」格式化,操作方式為「格式化字串.format(資料)」,輸出結果會將資料插入格式化字串的位置,下面的例子,會將 world 和 oxxo 兩個字串,分別插入字串中的兩個 {}。

a = 'hello {}, I am {}'
b = a.format('world', 'oxxo')
print(b)   # hello world, I am oxxo

{} 裡可以填入數字,數字表示「填入資料的順序」,如果將上面程式裡的 {} 加入數字,就會呈現不同的結果。

a = 'hello {1}, I am {0}'
b = a.format('world', 'oxxo')
print(b)   # hello oxxo, I am world ( world 和 oxxo 互換了 )

{} 裡可以填入具名引數,如果將上面程式裡的 {} 加入名稱,就會放入指定名稱的內容。

a = 'hello {m}, I am {n}'
b = a.format(m='world', n='oxxo')
print(b)   # hello world, I am oxxo

{} 裡可以填入字典的引數,如果將上面程式裡的 {} 加入對應的引數,就會放入指定的字典內容。

a = 'hello {0[x][m]}, I am {0[y][m]}'
b = {'x': {'m':'world', 'n':'oxxo'}, 'y':{'m':'QQ', 'n':'YY'}}
c = a.format(b)
print(c)    # hello world, I am QQ

新式的格式化字串和 % 定義略有不同,可以加入其他數值,來指定最小寬度、最大字元、對齊與精確度:

格式化數值 說明
: 開始需要加上冒號
不加東西、> 靠右對齊
< 靠左對齊
^ 置中對齊
填補字元 將不足最小寬度的空白,填滿指定字元
數字.數字 最小寬度.最大字元數,如果後方是 f (%f),第二個數字表示小數點位數

資料的型態也由 % 改為「:」表示。

格式化字串 轉換型態
:s 字串
:d 十進制整數
:x 十六進制整數
:o 八進制整數
:b 二進制整數
:f 十進制浮點數
:e 指數浮點數
:g 十進制或指數浮點數

下面的例子可以看到 {:-^10s} 會將 world 置中對齊,並將不足最小寬度的部分補上 - 的符號,{:^10.3f} 會讓 123.456789 只留下小數點三位。

a = 'hello {}, I am {}'.format('world','oxxo')
b = 'hello {:10s}, I am {:10s}'.format('world','oxxo')
c = 'hello {:>10s}, I am {:>10s}'.format('world','oxxo')
d = 'hello {:-^10s}, I am {:+^10s}'.format('world','oxxo')
e = 'hello {:-^10.3s}, I am {:-^10s}'.format('world','oxxo')
f = 'hello {:-^10.3s}, I am {:^10.3f}'.format('world',123.456789)
print(a)  # hello world, I am oxxo
print(b)  # hello world     , I am oxxo
print(c)  # hello      world, I am       oxxo
print(d)  # hello --world---, I am +++oxxo+++
print(e)  # hello ---wor----, I am ---oxxo---
print(f)  # hello ---wor----, I am  123.457

f-string

f-string 是 Python 3.6 加入的字串格式化功能,也是現在比較推薦的格式化方法,操作方式為「f{變數名稱或運算式}」( 開頭可以使用 f 或 F ),輸出結果會將變數或運算式的內容,放入指定的位置,下方的程式執行後,會將變數 a 和 b 的內容,放入 c 的字串裡。

a = 'world'
b = 'oxxo'
c = f'hello {a}, I am {b}'
print(c)   # hello world, I am oxxo

f-string 的格式化字串的定義和 .format 類似,可以加入其他數值,來指定最小寬度、最大字元、對齊與精確度。下面的例子可以看到 {b:+^10} 會將 oxxo 置中對齊,並將不足最小寬度的部分補上 + 的符號,{a:-<10.3} 會將 world 靠左對齊,並指取出 wor 三個字元,空白的部分補上 - 的符號。

a = 'world'
b = 'oxxo'
c = f'hello {a:<10s}, I am {b:>10s}'
d = f'hello {a:-<10s}, I am {b:+^10s}'
e = f'hello {a:-<10.3s}, I am {b:+^10.2s}'
f = f'hello {a.upper()}, I am {b.title()}'
print(c)   # hello world     , I am       oxxo
print(d)   # hello world-----, I am +++oxxo+++
print(e)   # hello wor-------, I am ++++ox++++
print(f)   # hello WORLD, I am Oxxo

了解原理後,就可以透過字串格式化的方式,實作「補零」的效果。

for i in range(1,101):
  print(f'{i:03d}',end=' , ')

'''
001 , 002 , 003 , 004 , 005 , 006 , 007 , 008 , 009 , 010 ,
011 , 012 , 013 , 014 , 015 , 016 , 017 , 018 , 019 , 020 ,
021 , 022 , 023 , 024 , 025 , 026 , 027 , 028 , 029 , 030 ,
031 , 032 , 033 , 034 , 035 , 036 , 037 , 038 , 039 , 040 ,
041 , 042 , 043 , 044 , 045 , 046 , 047 , 048 , 049 , 050 ,
051 , 052 , 053 , 054 , 055 , 056 , 057 , 058 , 059 , 060 ,
061 , 062 , 063 , 064 , 065 , 066 , 067 , 068 , 069 , 070 ,
071 , 072 , 073 , 074 , 075 , 076 , 077 , 078 , 079 , 080 ,
081 , 082 , 083 , 084 , 085 , 086 , 087 , 088 , 089 , 090 ,
091 , 092 , 093 , 094 , 095 , 096 , 097 , 098 , 099 , 100 ,
'''

更多教學

大家好,我是 OXXO,是個即將邁入中年的斜槓青年,我有個超過一千篇教學的 STEAM 教育學習網,有興趣可以參考下方連結呦~ ^_^


上一篇
( Day 7.1 ) Python 文字與字串 string
下一篇
( Day 8.1) Python 文字與字串 ( 常用方法 )
系列文
跟著 OXXO 一起學 Python101
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言