f-string 格式化字符串的用法

f-string 是 Python 中一种用于格式化字符串的强大工具,它允许你在字符串中插入变量、表达式以及其他值。你可以使用大括号 {} 来标识要插入的变量或表达式,并在字符串前添加一个 fF 前缀来指示这是一个 f-string。以下是一些 f-string 的用法示例:

  1. 插入变量:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# 输出: My name is Alice and I am 30 years old.
  1. 表达式计算:
x = 5
y = 10
result = f"The sum of {x} and {y} is {x + y}."
print(result)
# 输出: The sum of 5 and 10 is 15.
  1. 格式化数字输出:
price = 19.99
formatted_price = f"Price: ${price:.2f}"
print(formatted_price)
# 输出: Price: $19.99

在上面的示例中,{price:.2f} 表示将 price 变量格式化为带有两位小数的浮点数。

  1. 使用字典和列表:
person = {"name": "Bob", "age": 25}
fruits = ["apple", "banana", "cherry"]
message = f"{person['name']} is {person['age']} years old and likes {fruits[0]}."
print(message)
# 输出: Bob is 25 years old and likes apple.
  1. 调用函数:
def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))
# 输出: Hello, Alice!

这些示例展示了 f-string 的多种用法,它们使字符串格式化变得更加简单和直观。你可以在字符串中插入变量、表达式、字典键、列表元素,甚至调用函数,以满足不同的字符串格式化需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值