怎样将多个变量写入一个字符串
时间: 2023-06-11 10:05:19 浏览: 77
您可以使用格式化字符串或者字符串拼接的方式将多个变量写入一个字符串。
1. 格式化字符串
可以使用 f-string 或者 format 函数添加占位符 {} ,然后以后面的变量作为 format 方法的参数来填充字符串。
示例代码:
```
name = 'Alice'
age = 20
height = 1.65
result = f"My name is {name}, I'm {age} years old, and {height}m tall."
print(result)
# 输出:"My name is Alice, I'm 20 years old, and 1.65m tall."
```
或者使用 format 方法:
示例代码:
```
name = 'Alice'
age = 20
height = 1.65
result = "My name is {}, I'm {} years old, and {}m tall.".format(name, age, height)
print(result)
# 输出:"My name is Alice, I'm 20 years old, and 1.65m tall."
```
2. 字符串拼接
可以使用加号(+)或者 join 方法将多个字符串拼接起来。
示例代码:
```
name = 'Alice'
age = 20
height = 1.65
result = "My name is " + name + ", I'm " + str(age) + " years old, and " + str(height) + "m tall."
print(result)
# 输出:"My name is Alice, I'm 20 years old, and 1.65m tall."
```
或者使用 join 方法:
示例代码:
```
name = 'Alice'
age = 20
height = 1.65
result = ''.join(["My name is ", name, ", I'm ", str(age), " years old, and ", str(height), "m tall."])
print(result)
# 输出:"My name is Alice, I'm 20 years old, and 1.65m tall."
```