python 去掉\N
时间: 2023-07-22 18:10:01 浏览: 86
可以使用 `.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 去掉\t \n
你可以使用字符串的`strip()`方法来去掉字符串两端的空白字符,包括`\t`和`\n`。如果你想去掉字符串中间的空白字符,可以使用字符串的`replace()`方法来替换。例如:
```python
s = '\t hello \n world \t'
s = s.strip() # 去掉两端空白字符
s = s.replace('\t', '').replace('\n', '') # 去掉中间的空白字符
print(s) # 输出:hello world
```
另外,还可以使用正则表达式来去掉空白字符。例如:
```python
import re
s = '\t hello \n world \t'
s = re.sub(r'\s+', '', s) # 去掉所有空白字符
print(s) # 输出:helloworld
```