python中将变量按格式转为字符串的代码
时间: 2023-12-27 11:02:50 浏览: 83
可以使用字符串格式化操作符`%`或者字符串的`format()`方法将变量按格式转为字符串。
使用`%`操作符的示例:
```
name = 'Alice'
age = 25
height = 1.73
print('My name is %s, I am %d years old, and my height is %.2f meters.' % (name, age, height))
```
输出结果为:My name is Alice, I am 25 years old, and my height is 1.73 meters.
使用`format()`方法的示例:
```
name = 'Alice'
age = 25
height = 1.73
print('My name is {}, I am {} years old, and my height is {:.2f} meters.'.format(name, age, height))
```
输出结果与上面相同。
阅读全文