在Python中,你可以使用以下方法来忽略空白行:
使用 `strip()` 方法
`strip()` 方法可以移除字符串两端的空白字符(包括空格、换行符 `\n`、制表符 `\t` 等)。
如果一行文本经过 `strip()` 处理后变为空字符串,则该行为空白行,可以被过滤掉。
```python
lines = [
'Hello, world!',
'',
' ',
'This is a test.',
'\n'
]
filtered_lines = [line for line in lines if line.strip()]
print(filtered_lines) 输出: ['Hello, world!', 'This is a test.']
使用正则表达式
如果你需要更复杂的空行定义,比如包含某些特定字符但整体视为空行的情况,可以使用正则表达式来匹配并去除这些行。```pythonimport re
lines = [
'Hello, world!',
'\n',
'!@\n',
'This is a test.\n'
]
cleaned_lines = [line for line in lines if not re.match(r'^\s*$', line)]
print(cleaned_lines) 输出: ['Hello, world!', 'This is a test.']
文件操作中的空白行过滤
当处理存储在文件中的文本时,可以逐行读取文件内容,然后检查并忽略空行。
```python
def delblankline(infile, outfile):
with open(infile, 'r', encoding='utf-8') as infopen, open(outfile, 'w', encoding='utf-8') as outfopen:
for line in infopen.readlines():
if line.strip():
outfopen.write(line)
使用这些方法,你可以方便地从列表或文件中过滤掉空白行

