Python學習筆記10-f-string/format()的用法


前言

在Python中,有一種很方便的方式來格式化字串,就是使用f-string 或format()函式。f-string是一種字串前面加上f,可以在字串中使用大括號{}來插入變數或表達式。format()是另一種方法,可以在字串後面加上.format(),並在括號中傳入參數,來替換字串中的大括號{}。
f-string 和 format()的用法有以下幾個優點:
  • 可以讓字串更清楚易讀,不需要使用+號來連接字串和變數。
  • 可以使用多種格式化選項,如指定對齊方式、小數位數、進位制等。
  • 可以在字串中使用任何有效的Python表達式,如算術運算、函數呼叫等。
下面是一些f-string .format()的用法的範例:

串接變數與字串

# 宣告一些變數
name = "Alice"
age = 18
height = 1.65
score = 95.5
# 使用f-string來格式化字串,並插入變數
print(f"Hello, my name is {name}.") # Hello, my name is Alice.
print(f"I am {age} years old.") # I am 18 years old.
print(f"My height is {height} meters.") # My height is 1.65 meters.
# 使用.format()來格式化字串,並傳入參數
print("Hello, my name is {}. I am {} years old.".format(name, age)) 
# 輸出: Hello, my name is Alice. I am 18 years old.
print("My height is {} meters. My score is {} points.".format(height, score)) 
# 輸出: My height is 1.65 meters. My score is 95.5 points.

使用f-string和.format()來指定對齊方式

# 使用<表示左對齊,>表示右對齊,^表示置中
name = "Alice"
age = 20
# 使用f-string來指定對齊方式
message = f"Name: {name:<10} Age: {age:>5}"
print(message)
# 使用.format()來指定對齊方式
message = "Name: {:<10} Age: {:>5}".format(name, age)
print(message)
輸出結果:
Name: Alice      Age:    20
Name: Alice      Age:    20

使用f-string和.format()來指定進位制

#使用b表示二進位,o表示八進位,x表示十六進位
num = 42
print(f"{num:b} {num:o} {num:x}") # 101010 52 2a
print("{0:b} {0:o} {0:x}".format(num)) # 101010 52 2a
# 使用f-string和.format()來插入Python表達式,如算術運算、函數呼叫等
print(f"The area of a circle with radius {num} is {3.14 * num ** 2:.2f}.") 
# The area of a circle with radius 42 is 5541.76.
print("The area of a circle with radius {} is {:.2f}.".format(num, 3.14 * num ** 2)) 
# The area of a circle with radius 42 is 5541.76.
以上就是f-string .format()的用法和介紹,希望對你有所幫助。f-string .format()的用法是一種很靈活的字串格式化工具,可以讓我們的程式碼更簡潔和美觀。

感謝您閱讀本篇文章!我們很高興您能從中獲得一些有用的資訊。如果您喜歡這篇文章,請不要吝嗇您的支持,您可以:
  1. 按下愛心:這樣我們就知道您對這篇文章的喜愛程度,也可以讓更多人看到它。
  2. 分享文章:如果您認為這篇文章也能幫助其他人,請把它分享出去。
  3. 追蹤我們:如果您想持續收到更多類似的內容,請點擊追蹤按鈕。
  4. 支持我們:如果您願意,您也可以成為我們的贊助者。
為什麼會看到廣告
好奇的小仙人掌
好奇的小仙人掌
嗨!大家好,我是好奇的小仙人掌,一位無聊的大學生。作為一位學習程式的新手,我熱愛探索和學習各種新科技,期待與大家一同學習和成長!
留言0
查看全部
發表第一個留言支持創作者!