python str format
时间: 2024-03-01 08:47:42 浏览: 78
Python中的字符串格式化是一种用于创建格式化字符串的方法。它允许我们将变量、表达式或其他值插入到字符串中的特定位置。在Python中,有几种方法可以进行字符串格式化,其中最常用的是使用`str.format()`方法。
`str.format()`方法使用一对花括号 `{}` 作为占位符,用于指示要插入值的位置。我们可以在花括号中使用索引或关键字来指定要插入的值。下面是一些示例:
1. 使用位置参数:
```python
name = "Alice"
age = 25
print("My name is {} and I'm {} years old.".format(name, age))
```
输出:`My name is Alice and I'm 25 years old.`
2. 使用关键字参数:
```python
print("My name is {name} and I'm {age} years old.".format(name="Bob", age=30))
```
输出:`My name is Bob and I'm 30 years old.`
3. 使用索引:
```python
print("I have {0} apples and {1} oranges.".format(3, 5))
```
输出:`I have 3 apples and 5 oranges.`
4. 格式化数字:
```python
pi = 3.14159
print("The value of pi is {:.2f}".format(pi))
```
输出:`The value of pi is 3.14`
在`str.format()`方法中,我们还可以使用各种格式规范来控制输出的样式,例如指定字段宽度、精度、对齐方式等。更多关于格式规范的详细信息可以参考Python官方文档中的[格式化字符串语法](https://docs.python.org/3/library/string.html#format-specification-mini-language)。
阅读全文
相关推荐

















