其中数字输出要统一占位2格
时间: 2023-08-02 12:39:52 浏览: 42
好的,那么修改后的代码如下:
```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}"`,其中`{0}`表示第一个参数`exp`,`{1:2}`表示第二个参数`result`占位2格,不足2格则在前面填充空格。这样就可以输出统一占位2格的数字了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)