在Python中,格式化指的是将数据插入到字符串中的过程。这通常是通过使用特定的格式化符号和操作符来实现的,例如`%`运算符,它允许你定义字符串中的占位符,并将其他变量或值插入到这些占位符中。
1. 使用`%`运算符:
```python
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
2. 使用`str.format()`方法:
```python
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
3. 使用f-string(Python 3.6+):
```python
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
以上示例展示了如何使用不同的方法在Python中格式化字符串,以插入变量并按要求格式化输出