"".format用法
时间: 2024-09-12 19:16:43 浏览: 38
在Python中,`str.format()` 方法提供了一种格式化字符串的方法。它允许你通过大括号 `{}` 占位符将变量传递到字符串中,并可以控制变量的显示方式。以下是几种常见的用法:
1. 使用位置参数格式化字符串:
```python
name = "World"
greeting = "Hello, {}!".format(name)
print(greeting) # 输出: Hello, World!
```
2. 使用关键字参数:
```python
greeting = "Hello, {name}! You are {age} years old.".format(name="Alice", age=25)
print(greeting) # 输出: Hello, Alice! You are 25 years old.
```
3. 访问对象的属性或字典的键:
```python
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
person = Person("John", "Doe")
greeting = "Hello, {0.first_name} {0.last_name}!".format(person)
print(greeting) # 输出: Hello, John Doe!
```
4. 使用数字指定参数位置:
```python
greeting = "Hello, {1} {0}!".format("World", "Alice")
print(greeting) # 输出: Hello, Alice World!
```
5. 使用 `:` 进行填充、对齐、宽度和精度控制:
```python
number = 123456.789
# 填充和对齐
formatted_number = "{:*>10}".format(number) # 输出: *****123456.8
formatted_number = "{:*>10.2f}".format(number) # 输出: *****123456.79
# 宽度和精度
formatted_number = "{:8}".format(number) # 输出: 123456.8
formatted_number = "{:08.2f}".format(number) # 输出: 0123456.79
```
6. 使用 `+`, `-`, `=` 进行正负号控制:
```python
number = -123456.789
formatted_number = "{:>+10.2f}".format(number) # 输出: - 123456.79
formatted_number = "{:>+10.2f}".format(-number) # 输出: + 123456.79
formatted_number = "{:=+10.2f}".format(number) # 输出: +123456.79
```
阅读全文