Python的format函数
时间: 2023-10-23 13:10:23 浏览: 93
Python中的format函数可用于将一个字符串格式化为指定的字符串形式。它的基本语法如下:
```
formatted_string = "string to be formatted".format(argument1, argument2, ...)
```
在这个语法中,formatted_string是一个字符串,可以包含花括号{},这些花括号用于指示需要替换的位置。在format函数中,我们需要传递一个或多个参数,这些参数将替换花括号中的位置。
例如,下面的代码将字符串"Hello, my name is John"中的"John"替换为"Peter":
```
name = "Peter"
formatted_string = "Hello, my name is {}".format(name)
print(formatted_string)
```
输出:
```
Hello, my name is Peter
```
在format函数中,也可以使用命名参数。例如,下面的代码将字符串"Hello, my name is John"中的"John"替换为"Peter":
```
name = "Peter"
formatted_string = "Hello, my name is {name}".format(name=name)
print(formatted_string)
```
输出:
```
Hello, my name is Peter
```
除了位置参数和命名参数之外,format函数还可以指定格式化的方式,例如:
```
pi = 3.14159265359
formatted_string = "The value of pi is {:.2f}".format(pi)
print(formatted_string)
```
输出:
```
The value of pi is 3.14
```
在这个例子中,{:.2f}指示将pi格式化为保留两位小数的浮点数。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)