python中格式化
时间: 2023-08-08 16:11:21 浏览: 49
在Python中,你可以使用字符串的`format()`方法或者f-strings来进行格式化。
使用`format()`方法:
```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.`
你可以在花括号中使用索引来指定变量的顺序:
```python
name = "Bob"
age = 30
print("My name is {1} and I'm {0} years old.".format(age, name))
```
输出:`My name is Bob and I'm 30 years old.`
还可以通过指定格式来格式化变量:
```python
pi = 3.141592653589793
print("The value of pi is approximately {:.2f}.".format(pi))
```
输出:`The value of pi is approximately 3.14.`
使用f-strings:
```python
name = "Charlie"
age = 35
print(f"My name is {name} and I'm {age} years old.")
```
输出:`My name is Charlie and I'm 35 years old.`
f-strings的语法更简洁,可以直接在花括号中使用变量,也支持指定格式:
```python
pi = 3.141592653589793
print(f"The value of pi is approximately {pi:.2f}.")
```
输出:`The value of pi is approximately 3.14.`
这是Python中常用的字符串格式化方法,希望对你有帮助!如有其他问题,请随时提问。
相关推荐
![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_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)