程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

每天学点Python知识:如何删除空白

hfteth 2025-06-28 14:06:18 技术文章 3 ℃

在 Python 中,删除空白可以分为几种不同的情况,常见的是针对字符串或列表中空白字符的处理。


一、删除字符串中的空白

1. 删除字符串两端的空白(空格、\t、\n 等)

使用 .strip() 方法:

s = "   Hello, world!   "
clean_s = s.strip()
print(clean_s)  # 输出:'Hello, world!'
  • s.strip():去除首尾空白
  • s.lstrip():去除左侧空白
  • s.rstrip():去除右侧空白

2. 删除字符串中间的所有空白字符

使用 str.replace() 或正则表达式 re.sub():

方法一:replace()(只处理空格)

s = "Hello   world"
clean_s = s.replace(" ", "")
print(clean_s)  # 输出:'Helloworld'

方法二:使用 re.sub() 删除所有类型的空白字符

import re

s = "Hello\t world\nPython"
clean_s = re.sub(r"\s+", "", s)
print(clean_s)  # 输出:'HelloworldPython'

说明:

  • \s 表示所有空白字符(空格、制表符、换行符等)
  • + 表示一个或多个

3. 删除字符串中连续空格保留一个

如果想将多个空格变成一个空格:

import re

s = "Hello     world   Python"
clean_s = re.sub(r"\s+", " ", s)
print(clean_s)  # 输出:'Hello world Python'

二、删除列表中的空字符串或空白项

1. 删除列表中完全为空的项("" 或 " ")

lst = ["apple", "", "banana", " ", "cherry"]
clean_lst = [item for item in lst if item.strip()]
print(clean_lst)  # 输出:['apple', 'banana', 'cherry']

说明:

  • item.strip() 为 False 时表示空白项(包括空格、换行、制表符等)

三、删除文件中每行的空白(比如清理文本文件)

with open("example.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()

clean_lines = [line.strip() for line in lines if line.strip()]

with open("cleaned.txt", "w", encoding="utf-8") as f:
    f.writelines(line + "\n" for line in clean_lines)

说明:

  • line.strip() 去除首尾空白
  • if line.strip() 避免空行写入

四、删除多维结构中的空白(如嵌套列表)

data = [["a", " "], ["", "b", "c"], [" ", ""]]
clean_data = [[item for item in sublist if item.strip()] for sublist in data]
print(clean_data)  # 输出:[["a"], ["b", "c"], []]

总结:常用方法一览表

方法

说明

s.strip()

删除字符串首尾空白

s.replace(" ", "")

删除所有空格

re.sub(r"\s+", "")

删除所有空白字符

s.split() + ' '.join()

去除多余空格,保留单个空格

列表推导式 + strip()

删除列表中空白项

最近发表
标签列表