Python中f-string字符串格式化的使用
一、基本用法
name = "Alice"
age = 25
?
# 使用 f-string 嵌入變量
message = f"My name is {name} and I am {age} years old."
print(message)
?
# 輸出 My name is Alice and I am 25 years old.二、嵌入表達(dá)式
a = 5
b = 10
?
# 使用 f-string 嵌入表達(dá)式
result = f"The sum of {a} and is {a + b}."
print(result)
?
# 輸出 The sum of 5 and 10 is 15.三、格式化輸出
1、數(shù)字格式化
1.1浮點數(shù)格式化
語法:{value:.nf},其中 n 是保留的小數(shù)位數(shù)。
pi = 3.141592653589793
?
# 保留兩位小數(shù)
formatted_pi = f"Pi rounded to 2 decimal places: {pi:.2f}"
print(formatted_pi)
?
#輸出 Pi rounded to 2 decimal places: 3.141.2整數(shù)補零
語法:{value:0nd},其中 n 是總位數(shù),不足的部分用 0 填充。
number = 42
?
# 補零到 5 位
formatted_number = f"The number is {number:05d}"
print(formatted_number)
?
#輸出 The number is 000421.3千位分隔符
語法:{value:,},用逗號分隔千位。
population = 1234567890
?
# 添加千位分隔符
formatted_population = f"The world population is {population:,}"
print(formatted_population)
?
#輸出 The world population is 1,234,567,8901.4百分比格式化
語法:{value:.n%},其中 n 是保留的小數(shù)位數(shù)。
ratio = 0.4567
?
# 格式化為百分比,保留兩位小數(shù)
formatted_ratio = f"The ratio is {ratio:.2%}"
print(formatted_ratio)
?
#輸出 The ratio is 45.67%2、字符串格式化
2.1對齊和填充
語法:{value:width} 或 {value:<width}、{value:>width}、{value:^width},其中 width 是總寬度。
<:左對齊>:右對齊^:居中對齊
name = "Alice"
?
# 左對齊,總寬度為 10,用 ' ' 填充
formatted_name = f"Name: {name:<10}!"
print(formatted_name)
?
# 右對齊,總寬度為 10,用 '*' 填充
formatted_name = f"Name: {name:*>10}!"
print(formatted_name)
?
# 居中對齊,總寬度為 10,用 '=' 填充
formatted_name = f"Name: {name:=^10}!"
print(formatted_name)
?
# 輸出
Name: Alice !
Name: *****Alice!
Name: ==Alice===!2.2截斷字符串
語法:{value:.n},其中 n 是保留的字符數(shù)。
long_text = "This is a very long string."
?
# 截斷為前 10 個字符
formatted_text = f"Truncated: {long_text:.10}"
print(formatted_text)
?
#輸出 Truncated: This is a3、日期和時間格式化
3.1格式化日期
使用 strftime 方法結(jié)合 f-string 格式化日期。
from datetime import datetime
?
now = datetime.now()
?
# 格式化日期
formatted_date = f"Today is {now:%Y-%m-%d}"
print(formatted_date)
?
#輸出 Today is 2023-10-053.2格式化時間
from datetime import datetime
?
now = datetime.now()
?
# 格式化時間
formatted_time = f"The time is {now:%H:%M:%S}"
print(formatted_time)
?
#輸出 The time is 14:35:224、其他格式化
4.1科學(xué)計數(shù)法
語法:{value:.ne},其中 n 是保留的小數(shù)位數(shù)。
number = 1234567890
?
# 科學(xué)計數(shù)法,保留兩位小數(shù)
formatted_number = f"Scientific notation: {number:.2e}"
print(formatted_number)
?
#輸出 Scientific notation: 1.23e+094.2二進(jìn)制、八進(jìn)制、十六進(jìn)制
語法:
- 二進(jìn)制:
{value:b} - 八進(jìn)制:
{value:o} - 十六進(jìn)制:
{value:x}(小寫)或{value:X}(大寫)
number = 255
?
# 二進(jìn)制
binary = f"Binary: {number:b}"
print(binary)
?
# 八進(jìn)制
octal = f"Octal: {number:o}"
print(octal)
?
# 十六進(jìn)制
hexadecimal = f"Hexadecimal: {number:x}"
print(hexadecimal)
?
#輸出
Binary: 11111111
Octal: 377
Hexadecimal: ff四、調(diào)用函數(shù)和方法
name = "alice"
?
# 調(diào)用字符串的 title() 方法
formatted_name = f"Hello, {name.title()}!"
print(formatted_name)
?
# 輸出 Hello, Alice!字符串title方法:
將所有單詞的首字母大寫包括像it's中的's
與capitalize() 的區(qū)別:capitalize() 僅將整個字符串的第一個單詞的首字母大寫,其余字母小寫。
五、使用字典和列表
person = {"name": "Bob", "age": 30}
?
# 訪問字典中的值
info = f"{person['name']} is {person['age']} years old."
print(info)
?
numbers = [1, 2, 3, 4, 5]
?
# 訪問列表中的元素
summary = f"The first number is {numbers[0]} and the last number is {numbers[-1]}."
print(summary)
?
# 輸出
Bob is 30 years old.
The first number is 1 and the last number is 5.六、多行f-string
name = "Charlie"
age = 35
?
# 多行 f-string
message = f"""
Name: {name}
Age: {age}
"""
print(message)
?
# 輸出
Name: Charlie
Age: 35七、嵌套f-string
a = 5
b = 10
?
# 嵌套 f-string
result = f"The sum of {a} and is {f'{a + b}'}."
print(result)
?
# 輸出 The sum of 5 and 10 is 15.到此這篇關(guān)于Python中f-string字符串格式化的使用的文章就介紹到這了,更多相關(guān)Python f-string字符串格式化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python&Matlab實現(xiàn)螞蟻群算法求解最短路徑問題的示例
本文主要介紹了Python&Matlab實現(xiàn)螞蟻群算法求解最短路徑問題的示例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
穩(wěn)扎穩(wěn)打?qū)WPython之容器 可迭代對象 迭代器 生成器專題講解
在剛開始學(xué)Python的時候,是不是經(jīng)常會聽到大佬們在講容器、可迭代對象、迭代器、生成器、列表/集合/字典推導(dǎo)式等等眾多概念,其實這不是大佬們沒事就擱那扯專業(yè)術(shù)語來裝B,而是這些東西都得要明白的,光知道字符串、列表等基礎(chǔ)還是不夠的,尤其是在Python的數(shù)據(jù)結(jié)構(gòu)方面2021-10-10
Python實現(xiàn)對桌面進(jìn)行實時捕捉畫面的方法詳解
最近在研究目標(biāo)檢測方面的小東西,需要到對桌面進(jìn)行實時捕捉畫面。所以本文來用Python實現(xiàn)簡單的對桌面進(jìn)行實時捕捉畫面,感興趣的可以了解一下2023-01-01
PyTorch使用Tricks:Dropout,R-Dropout和Multi-Sample?Dropout方式
這篇文章主要介紹了PyTorch使用Tricks:Dropout,R-Dropout和Multi-Sample?Dropout方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02
Python 3.3實現(xiàn)計算兩個日期間隔秒數(shù)/天數(shù)的方法示例
這篇文章主要介紹了Python 3.3實現(xiàn)計算兩個日期間隔秒數(shù)/天數(shù)的方法,結(jié)合實例形式較為詳細(xì)的分析了基于Python3.3的日期時間轉(zhuǎn)換與運算相關(guān)操作技巧,需要的朋友可以參考下2019-01-01

