python readlines怎么去掉\\n
时间: 2023-04-30 15:00:56 浏览: 544
可以使用 `.strip()` 方法去掉每行末尾的 '\n'。例如:
```
with open("file.txt", "r") as f:
lines = f.readlines()
for line in lines:
line = line.strip()
print(line)
```
也可以使用列表推导式:
```
with open("file.txt", "r") as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
print(lines)
```
相关问题
python readlines 去除\n
可以使用strip()函数去除每行末尾的\n,代码如下:
with open('file.txt', 'r') as f:
lines = [line.strip() for line in f.readlines()]
python readlines怎么去掉\n
可以使用 str.strip() 方法去掉字符串中的换行符。
示例:
```
with open("file.txt", "r") as f:
lines = f.readlines()
# use strip method to remove '\n'
stripped_lines = [line.strip() for line in lines]
```
也可以在读取文件时使用 `read().splitlines()` 方法,该方法会自动去掉换行符。
示例:
```
with open("file.txt", "r") as f:
lines = f.read().splitlines()
```
阅读全文