一、基本概念
字元串格式化指的是把一組值按照指定格式進行轉換成字元串的過程,常用的方式有「%」和「format()」兩種。其中,「%」方式最為常用,而且與C語言的格式化輸出功能相似。
格式化字元串的基本語法是:字元串 % 值,其中,字元串中的格式化規則以「%」(模板)字元開頭,後面跟著一個或多個格式化字元,表示格式化的方式,最終的結果是將格式化字元和值進行替換。
二、%方式的使用
1、字元串、整數、浮點數、布爾值等的使用
# 字元串格式化 name = "Alice" print("Hello, %s!" % name) # 整數格式化 number = 34 print("Your lucky number is %d." % number) # 浮點數格式化 pi = 3.1415926 print("Pi is approximately %f." % pi) # 布爾值格式化 flag = False print("The answer is %s." % flag)
2、大小寫、千位分隔符、進位等的使用
# 大小寫 s = "world" print("Hello, %s!" % s.upper()) print("Hello, %s!" % s.capitalize()) print("Hello, %s!" % s.title()) # 千位分隔符 number = 1000000 print("The population of the city is %d." % number) print("The population of the city is %,d." % number) # 進位 number = 10 print("The decimal number is %d." % number) print("The binary number is 0b%02x." % number) print("The hexadecimal number is 0x%02x." % number)
三、format()方式的使用
1、基本用法
# 使用位置參數 print("The first letter in {0} is {0[0]}.".format("Python")) # 使用關鍵字參數 print("The temperature of the {city} is {temp} degrees Celsius.".format(city="Beijing", temp=27)) # 使用屬性欄位 class Person: def __init__(self, name, age): self.name = name self.age = age p = Person("Tom", 22) print("My name is {0.name}, and I am {0.age} years old.".format(p))
2、填充、對齊和寬度
s = "apple" print("|{:>10}|".format(s)) # 右對齊 print("|{:<10}|".format(s)) # 左對齊 print("|{:^10}|".format(s)) # 居中對齊 # 填充 print("|{:*^10}|".format(s)) # 使用*進行填充 print("|{:*^10.2f}|".format(3.14159)) # 小數點位數為2 # 寬度 print("|{0:10}|{1:5}|".format("Name", "Age")) print("|{0:10}|{1:5d}|".format("Tom", 22)) print("|{0:10}|{1:5d}|".format("Jerry", 25))
四、f-string方式的使用
f-string是Python3.6新增的一種字元串格式化方式,它簡單易用,可以把表達式直接嵌入到字元串中。
1、使用方法
name = "Alice" print(f"Hello, {name}!") age = 22 print(f"I am {age} years old.") pi = 3.1415926 print(f"Pi is approximately {pi:.2f}.")
2、支持運算、函數調用等
print(f"3 + 4 = {3 + 4}.") print(f"The first letter in {'Python'.upper()} is {'Python'[0]}.") def greet(name): return f"Hello, {name}!" print(greet("Bob"))
五、總結
Python字元串格式化是Python中常用的一種字元串處理方式,可以使用「%」、「format()」和f-string方式進行。其中,「%」方式最為常用,適用於大多數格式化場景,還支持C語言模板字元串和格式化標誌;「format()」方式則更加靈活,支持位置參數、關鍵字參數、屬性欄位、填充和對齊等功能;而f-string則是Python3.6新增的一種字元串格式化方式,簡單易用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/197302.html