2024年1月1日 星期一

[Python] Python String format 字串格式化 : (1) 舊式字串格式化 %-formatting (2) 新式字串格式化 str.format() (3) 字串插值 f-string (Formatted String Literal) (4) Template Strings

.


Python 在處理字串時, 由於版本的演變, 有太多種方法, 所以很容易搞混. 筆記整理一下.
.


(1) 舊式字串格式化 %-formatting:

string interpolation

初代 format string, 這是類似 C語言 printf 語法, 使用 % 格式, 
例如: %s (字串), %d (十進位整數), %f (浮點數), 將 tuple 中的一組變量依照指定字串格式輸出.

# Example 1.1:
text = 'World'
print('Hello %s' % text)
# Hello world


# Example 1.2:
name = "John"
age = 23
print('%s is %d years old.' % (name, age))
# John is 23 years old.


# Example 1.3:
print('%x' % 11)  # 轉成十六進位
# b

(2) 新式字串格式化 str.format()

Python 2.6 (發布於 2008 年), 開始有新式字串格式化 str.format(), 透過{} 和 format 來代替 % 運算符號.

# Example 2.1:
text = 'World'
print('Hello {0}'.format(text))
# Hello world
print('Hello {}'.format(text))
# Hello world


# Example 2.2:
name = "John"
age = 23
print('{0} is {1} years old.'.format(name, age))
# John is 23 years old.
print('{} is {} years old.'.format(name, age))
# John is 23 years old.


# Example 2.3:
print('{:x}'.format(11))  # 轉成十六進位
# b


# Example 2.4:
print('{:.2f}'.format(3.1416))  # 保留小數點後兩位
# 3.14


# Example 2.5:
print('{:+.2f}'.format(3.1416))  # 帶符號保留小數點後兩位
# +3.14


細節可以參考 Ref3: Python format 格式化函数


(3) 字串插值 f-string (Formatted String Literal)

Python 3.6 (發布於 2016 年) 新增 f-string, 解決變量不易閱讀以及變量超長的問題.

# Example 3.1:
text = 'World'
print(f'Hello {text}')
# Hello world



# Example 3.2:
name = "John"
age = 23
print(f'{name} is {age} years old.')
# John is 23 years old.


# Example 3.3:
print(f'{11:x}')  # 轉成十六進位
# b


# Example 3.4:
print(f'{3.1416:.2f}')  # 保留小數點後兩位
# 3.14
a = 3.1416
print(f'{a:.2f}')  # 保留小數點後兩位
# 3.14


# Example 3.5:
print(f'{3.1416:+.2f}')  # 帶符號保留小數點後兩位
# +3.14


細節可以參考 Ref4: 制霸 Python f-string 各種格式使用方法


(4) Template Strings:

# Example 4.1:
from string import Template
name = 'Bob'
t = Template('Hey, $name!')
t.substitute(name=name)
# 'Hey, Bob!'


--- --- ---

同場加映 : Python String 字串 join() 語法


# Example 5.1:
chars = ['P', 'y', 't', 'h', 'o', 'n']
text = "".join(chars)
print(text)  # 顯示:Python


# Example 5.2:
chars = ['P', 'y', 't', 'h', 'o', 'n']
text = "##".join(chars)
print(text)  # 顯示:P##y##t##h##o##n


# Example 5.3:
words = ["Python", "is", "awesome"]
text = " ".join(words)
print(text)  # 顯示:Python is awesome



--- --- ---

Ref2: 如何使用 Python 進行字串格式化

Ref3: Python format 格式化函数

Ref4: 制霸 Python f-string 各種格式使用方法

Ref5: Python String Formatting Best Practices

// End.

沒有留言:

張貼留言