创建文本文件“A.txt”,其中每行包含一段英文,编写程序,读取文件的全部内容,以及一行中包含字符最多和字符最少的分别在第几行。python
时间: 2024-03-25 09:38:03 浏览: 21
您可以使用以下 Python 代码实现:
```python
filename = 'A.txt'
max_line = ''
min_line = ''
max_len = 0
min_len = float('inf')
with open(filename, 'r') as file:
lines = file.readlines()
for i, line in enumerate(lines):
line = line.strip()
if len(line) > max_len:
max_len = len(line)
max_line = f'Line {i+1}'
if len(line) < min_len:
min_len = len(line)
min_line = f'Line {i+1}'
print(f'The line with the most characters is {max_line}, with {max_len} characters')
print(f'The line with the least characters is {min_line}, with {min_len} characters')
```
这个程序首先打开指定的文件,逐行读取文件内容,使用 `strip()` 方法去掉每行的空格和换行符。然后,它通过比较每行的长度来找到字符最多和字符最少的行。最后,程序输出结果,告诉您哪些行包含最多和最少的字符。
阅读全文
相关推荐

















