上面那个代码的输出我想把print(exp + '=' + str(result))换成键值的形式,用format
时间: 2024-03-14 15:42:46 浏览: 8
好的,你可以使用格式化字符串的方式将表达式和结果输出成键值对的形式。修改后的代码如下:
```python
with open("test5.txt", "r") as f:
expressions = f.read().split()
for exp in expressions:
if '+' in exp:
a, b = exp.split('+')
result = int(a) + int(b)
print("{0}={1:2}".format(exp, result))
elif '-' in exp:
a, b = exp.split('-')
result = int(a) - int(b)
print("{0}={1:2}".format(exp, result))
elif '*' in exp:
a, b = exp.split('*')
result = int(a) * int(b)
print("{0}={1:2}".format(exp, result))
elif '/' in exp:
a, b = exp.split('/')
result = int(a) / int(b)
print("{0}={1:2}".format(exp, result))
else:
print("Invalid expression:", exp)
```
在 `print` 语句中,使用了格式化字符串的语法 `{0}={1:2}`,表示将第一个参数 `exp` 输出为字符串,第二个参数 `result` 输出为占位2格的整数。这样就可以将表达式和结果输出成键值对的形式了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)