python中f-string的所有用法
时间: 2024-04-09 08:29:02 浏览: 153
f-string提供了多种用法来格式化字符串。以下是一些常见的用法示例:
1. 插入变量:
```python
name = "Alice"
age = 25
message = f"My name is {name} and I am {age} years old."
```
2. 插入表达式:
```python
x = 5
y = 10
result = f"The sum of {x} and {y} is {x + y}."
```
3. 格式化数字:
```python
pi = 3.14159265359
formatted_pi = f"Value of pi: {pi:.2f}"
```
4. 调用函数:
```python
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
```
5. 访问对象属性或方法:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"My name is {self.name} and I am {self.age} years old."
person = Person("Alice", 25)
intro = person.introduce()
```
6. 使用字典键值:
```python
person = {"name": "Alice", "age": 25}
message = f"My name is {person['name']} and I am {person['age']} years old."
```
7. 使用运算符:
```python
x = 5
y = 10
message = f"The result of {x} * {y} is {x * y if x > y else y - x}."
```
这些只是一些常见的用法示例,f-string还支持更复杂的表达式和格式化选项。你可以根据自己的需求来使用f-string进行字符串格式化。
阅读全文