当前位置: 代码网 > it编程>前端脚本>Python > Python中f-string字符串格式化的使用

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

2025年05月07日 Python 我要评论
一、基本用法name = "alice" age = 25 ​ # 使用 f-string 嵌入变量 message = f"my name is {name} and i am {age} year

一、基本用法

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二进制、八进制、十六进制

语法:

  • 二进制:{value:b}
  • 八进制:{value:o}
  • 十六进制:{value:x}(小写)或 {value:x}(大写)
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方法:

  • 将所有单词的首字母大写包括像it's中的's

  • 与capitalize() 的区别: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 {b} is {f'{a + b}'}."
 print(result)
 ​
 # 输出 the sum of 5 and 10 is 15.

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

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com