Python格式化字符串的几种方式
时间: 2023-11-05 20:06:45 浏览: 69
1. 使用 % 运算符进行字符串格式化:
```python
name = 'Alice'
age = 25
print('My name is %s and I am %d years old.' % (name, age))
```
2. 使用 format() 方法进行字符串格式化:
```python
name = 'Alice'
age = 25
print('My name is {} and I am {} years old.'.format(name, age))
```
3. 使用 f-string 进行字符串格式化(Python 3.6+):
```python
name = 'Alice'
age = 25
print(f'My name is {name} and I am {age} years old.')
```
4. 使用模板字符串进行字符串格式化(需要导入 string 模块):
```python
from string import Template
name = 'Alice'
age = 25
template = Template('My name is $name and I am $age years old.')
print(template.substitute(name=name, age=age))
```
相关问题
Python中格式化字符串的几种方式
在Python中,有几种方式可以格式化字符串:
1. 使用百分号(%)进行格式化:这是一种传统的方式,通过在字符串中使用占位符和格式化字符来替换相应的值。例如:
```
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
```
输出:My name is Alice and I am 25 years old.
2. 使用format()方法进行格式化:这是一种更加灵活和推荐的方式,通过在字符串中使用花括号{}作为占位符,并使用format()方法来传递相应的值。例如:
```
name = "Bob"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
```
输出:My name is Bob and I am 30 years old.
3. 使用f-string进行格式化(Python 3.6及以上版本):这是一种最简洁和直观的方式,通过在字符串前加上字母"f",并在花括号{}中直接引用变量来进行格式化。例如:
```
name = "Charlie"
age = 35
print(f"My name is {name} and I am {age} years old.")
```
输出:My name is Charlie and I am 35 years old.
python中格式化字符串的几种方式
Python中格式化字符串的几种方式有:
1. 使用 % 运算符格式化字符串,将需要插入的变量放入字符串中的占位符中,比如:
```
name = 'Jack'
age = 18
print('My name is %s, and I am %d years old.' % (name, age))
```
2. 使用 str.format() 方法格式化字符串,用 {} 表示占位符,比如:
```
name = 'Jack'
age = 18
print('My name is {}, and I am {} years old.'.format(name, age))
```
3. 使用 f-strings (Python 3.6+ 版本才支持),在字符串前加上 f,使用 { } 表示占位符,比如:
```
name = 'Jack'
age = 18
print(f'My name is {name}, and I am {age} years old.')
```
4. 使用模板字符串 (string.Template) 实现字符串的格式化,用 $ 表示占位符,比如:
```
from string import Template
name = 'Jack'
age = 18
t = Template('My name is $name, and I am $age years old.')
print(t.substitute(name=name, age=age))
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_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://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)