12 + 23 = 35 6 * 9 = 54 24 - 5 = 19 72 / 6 = 12.0 5 - 29 = -24 43 + 3 = 46我想让输出结果是这样的,每个数字占位为2,也就是%2d
时间: 2024-03-14 14:42:54 浏览: 39
好的,你可以在 `print` 语句中使用 `%2d` 格式化字符串的语法,将表达式和结果输出为占位为2的整数。修改后的代码如下:
```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("%2d + %2d = %2d" % (int(a), int(b), result))
elif '-' in exp:
a, b = exp.split('-')
result = int(a) - int(b)
print("%2d - %2d = %2d" % (int(a), int(b), result))
elif '*' in exp:
a, b = exp.split('*')
result = int(a) * int(b)
print("%2d * %2d = %2d" % (int(a), int(b), result))
elif '/' in exp:
a, b = exp.split('/')
result = int(a) / int(b)
print("%2d / %2d = %2.1f" % (int(a), int(b), result))
else:
print("Invalid expression:", exp)
```
在 `print` 语句中,使用了 `%2d` 和 `%2.1f` 格式化字符串的语法,表示将参数输出为占位为2的整数和占位为2的浮点数。这样就可以将表达式和结果输出为占位为2的整数了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)