python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python f-string字符串格式化

Python中f-string字符串格式化的使用

作者:shyoutou

本文介绍了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.

二、嵌入表达式

a = 5
 b = 10
 ​
 # 使用 f-string 嵌入表达式
 result = f"The sum of {a} and {b} is {a + b}."
 print(result)
 ​
 # 输出 The sum of 5 and 10 is 15.

三、格式化输出

1、数字格式化

1.1浮点数格式化

语法:{value:.nf},其中 n 是保留的小数位数。

pi = 3.141592653589793
 ​
 # 保留两位小数
 formatted_pi = f"Pi rounded to 2 decimal places: {pi:.2f}"
 print(formatted_pi)
 ​
 #输出 Pi rounded to 2 decimal places: 3.14

1.2整数补零

语法:{value:0nd},其中 n 是总位数,不足的部分用 0 填充。

number = 42
 ​
 # 补零到 5 位
 formatted_number = f"The number is {number:05d}"
 print(formatted_number)
 ​
 #输出 The number is 00042

1.3千位分隔符

语法:{value:,},用逗号分隔千位。

population = 1234567890
 ​
 # 添加千位分隔符
 formatted_population = f"The world population is {population:,}"
 print(formatted_population)
 ​
 #输出 The world population is 1,234,567,890

1.4百分比格式化

语法:{value:.n%},其中 n 是保留的小数位数。

ratio = 0.4567
 ​
 # 格式化为百分比,保留两位小数
 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 是总宽度。

  1. <:左对齐
  2. >:右对齐
  3. ^:居中对齐
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 是保留的字符数。

long_text = "This is a very long string."
 ​
 # 截断为前 10 个字符
 formatted_text = f"Truncated: {long_text:.10}"
 print(formatted_text)
 ​
 #输出 Truncated: This is a

3、日期和时间格式化

3.1格式化日期

使用 strftime 方法结合 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-05

3.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:22

4、其他格式化

4.1科学计数法

语法:{value:.ne},其中 n 是保留的小数位数。

number = 1234567890
 ​
 # 科学计数法,保留两位小数
 formatted_number = f"Scientific notation: {number:.2e}"
 print(formatted_number)
 ​
 #输出 Scientific notation: 1.23e+09

4.2二进制、八进制、十六进制

语法:

number = 255
 ​
 # 二进制
 binary = f"Binary: {number:b}"
 print(binary)
 ​
 # 八进制
 octal = f"Octal: {number:o}"
 print(octal)
 ​
 # 十六进制
 hexadecimal = f"Hexadecimal: {number:x}"
 print(hexadecimal)
 ​
 #输出
 Binary: 11111111
 Octal: 377
 Hexadecimal: ff

四、调用函数和方法

name = "alice"
 ​
 # 调用字符串的 title() 方法
 formatted_name = f"Hello, {name.title()}!"
 print(formatted_name)
 ​
 # 输出 Hello, Alice!

字符串title方法:

五、使用字典和列表

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 {b} is {f'{a + b}'}."
 print(result)
 ​
 # 输出 The sum of 5 and 10 is 15.

到此这篇关于Python中f-string字符串格式化的使用的文章就介绍到这了,更多相关Python f-string字符串格式化内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文