format函数的用法
时间: 2023-06-23 09:56:17 浏览: 61
`format()` 函数是 Python 中常用的字符串格式化方法,用于将不同类型的数据转换为字符串并按照指定的格式进行排列和组合。
`format()` 函数的基本语法如下:
```
formatted_string = "string {} string {}".format(value1, value2)
```
其中,花括号 `{}` 表示占位符,可以在其中指定要插入的值的位置,可以使用数字或名称来指定占位符的位置。括号中的值可以是任何类型的数据,如字符串、整数、浮点数等。例如:
```
name = "John"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
```
输出结果为:
```
My name is John and I am 30 years old.
```
在 `format()` 函数中,还可以指定格式化的方式,例如:
- `{:.2f}` 表示保留两位小数的浮点数
- `{:+d}` 表示带符号的整数
- `{:<10}` 表示左对齐的字符串,总长度为 10
- `{:^10}` 表示居中对齐的字符串,总长度为 10
- `{:<10.2f}` 表示左对齐的保留两位小数的浮点数,总长度为 10
例如:
```
x = 123.456
print("{:.2f}".format(x)) # 输出:123.46
y = -10
print("{:+d}".format(y)) # 输出:-10
s = "hello"
print("{:<10}".format(s)) # 输出:hello
print("{:^10}".format(s)) # 输出: hello
print("{:<10.2f}".format(x))# 输出:123.46
```
总之,`format()` 函数提供了灵活且强大的字符串格式化功能,可以满足多种不同的需求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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://csdnimg.cn/download_wenku/file_type_ask_c1.png)