python中format函数的用法
时间: 2023-07-14 09:00:07 浏览: 48
Python中的format函数可以用来格式化字符串。它可以将变量值替换到字符串中的占位符中。
格式: "string {var} string {var}...".format(var1, var2,...)
例如:
print("My name is {} and I am {} years old.".format("John", 30))
# Output: My name is John and I am 30 years old.
也可以用编号来指定变量的位置:
print("My name is {0} and I am {1} years old.".format("John", 30))
# Output: My name is John and I am 30 years old.
还可以用关键字参数:
print("My name is {name} and I am {age} years old.".format(name="John", age=30))
# Output: My name is John and I am 30 years old.
相关问题
python中format函数用法
好的,关于Python中format函数用法,我可以为您解答。format函数是Python中一个用于格式化字符串的函数,它可以让我们以特定的方式将变量插入到字符串中。它的基本用法是将一个字符串作为模板,然后使用大括号{}表示要插入变量的位置。例如:str = "我的名字是{},我今年{}岁。".format("小明", 20)。在这个例子中,format函数将"小明"和"20"插入到了字符串中。此外,format函数还支持指定变量的数据类型、对齐方式、精度等操作。您可以在Python官方文档中查看更详细的介绍。
Python中format函数用法
Python中的format函数是一种字符串格式化的方法,它可以根据传入的参数,将占位符替换为具体的值。格式化字符串中使用花括号 {} 表示占位符,可以通过位置、关键字或者名称来指定替换的值。
下面是一些常用的用法示例:
1. 位置参数
```python
name = '张三'
age = 18
print('我的名字是{},我{}岁了。'.format(name, age))
```
输出结果为:
```
我的名字是张三,我18岁了。
```
2. 关键字参数
```python
print('我的名字是{name},我{age}岁了。'.format(name='李四', age=20))
```
输出结果为:
```
我的名字是李四,我20岁了。
```
3. 格式化数值
```python
pi = 3.1415926
print('π的值是{:.2f}'.format(pi))
```
输出结果为:
```
π的值是3.14
```
4. 格式化日期
```python
from datetime import datetime
now = datetime.now()
print('今天是{:%Y-%m-%d %H:%M:%S}'.format(now))
```
输出结果为:
```
今天是2021-08-04 15:30:00
```
这只是format函数的一部分用法,具体的用法可以查看Python官方文档。