一、什麼是字元串格式化
在Python中,字元串格式化是指把一系列值插入到字元串中,這些值可以是數字、字元串或其它的Python對象。字元串格式化通常用於生成輸出。
Python提供了多種字元串格式化方法,使用不同的方式可以避免拼接字元串時出現繁瑣、錯誤的問題。接下來介紹常見的字元串格式化方法。
二、百分號格式化
百分號格式化使用百分號(%)作為佔位符,並給出一個元組來指出需要插入的元素。我們可以使用字元串的格式操作符%將值轉換成一個字元串,並將該值插入列格式化的佔位符中。
# 單個變數百分號格式化 name = 'Tom' age = 18 text = 'My name is %s, I am %d years old.' % (name, age) print(text) # 多個變數百分號格式化 name_1 = 'Jack' age_1 = 22 name_2 = 'Lucy' age_2 = 20 text_1 = 'My name is %s, I am %d years old. My friend is %s, he is %d years old.' % (name_1, age_1, name_2, age_2) print(text_1)
三、format格式化
format方法就是將字元串當中的佔位符替換成傳入的參數進行格式化,常見的佔位符有{}和{:}。在{}中可以定義佔位符,比如{0}{1}。
# 單個變數format格式化 name = 'Tom' age = 18 text = 'My name is {}, I am {} years old.'.format(name, age) print(text) # 格式化數字 number = 12345.6789 print('This is float:{:.3f}'.format(number)) print('This is int:{:d}'.format(int(number)))
四、f-string格式化
f-string是Python 3.6之後新加的一種字元串格式化方式,它在字元串前面加上前綴”f”,並在字元串中通過圓括弧{}來包含要自動計算的表達式,十分方便。
# 單個變數f-string格式化 name = 'Tom' age = 18 text = f'My name is {name}, I am {age} years old.' print(text) # 計算表達式f-string格式化 a = 10 b = 20 text_1 = f'The sum of {a} and {b} is {a+b}' print(text_1)
五、總結
Python提供了多種字元串格式化方法,使用不同的方式可以避免拼接字元串時出現繁瑣、錯誤的問題。在實際編寫代碼時,我們可以根據需求選用不同的字元串格式化方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/271461.html