python中字符串去空格的各种姿势 python中字符串如何去除空格

在 Python 中,去除字符串中的空格是一个常见的操作。让我们盘点下python中常用的的去空格姿势吧。


一、两头空

两头空:只去除字符串两端的空格。

1. 使用 strip()

strip() 方法可以去除字符串两端的空格和换行

示例:

text = " Hello, World! "
result = text.strip()
print(result) # 输出: "Hello, World!"

2. 去除指定字符(如空格、换行)

如果想去除特定的字符,可以传递参数给 strip()

示例:

text = " \nHello, World!"
print(len(text)) # 16
result = text.strip("!")
print(len(result)) # 15
print(result) # 输出: " \nHello, World"


二、左侧空/右侧空

1. 使用 lstrip()

lstrip() 方法去除字符串左侧的空格。

示例:

text = " Hello, World! "
result = text.lstrip()
print(result) # 输出: "Hello, World! "

2. 使用 rstrip()

rstrip() 方法去除字符串右侧的空格。

示例:

text = " Hello, World! "
result = text.rstrip()
print(result) # 输出: " Hello, World!"

三、指不定哪里空

1. 使用 replace()

replace() 方法可以替换字符串中的所有空格,包括中间的空格。

示例:

text = " Hello, World! "
result = text.replace(" ", "")
print(result) # 输出: "Hello,World!"

replace()还有个count参数,可以指定替换次数(从左开始哦!)

示例:

text = " Hello, World! "
result = text.replace(" ", "",1)
print(result) # 输出: "Hello, World! "

2. 使用正则表达式 re.sub()

如果想去除所有空格(包括换行符、制表符等),可以使用正则表达式。

示例:

import re
text = " Hello,\n\t World! "
result = re.sub(r"\s+", "", text)
print(result) # 输出: "Hello,World!"
  • \s 匹配所有空白字符(包括空格、制表符、换行符等)。
  • \s+ 表示匹配一个或多个空白字符。

一般情况下我不会用这种方法,太麻烦!除非有更变态要求!比如:" Hello,      world! " 去掉逗号后的空格保留其他的空格。

import re
text = " Hello,      world! "
result = re.sub(r",\s+", ",", text)
print(result) # 输出: " Hello,world! "


四、逐个击破法

所谓逐个击破就是通过遍历来去除。

1. 使用字符串拆分和拼接

通过 split() 方法拆分字符串,然后用单个空格拼接。

示例:

text = "Hello, World! How are you?"
result = "".join(text.split())
print(result) # 输出: "Hello,World!Howareyou?"

2. 使用for循环

text = "Hello, World! How are you?"
result = ''
for char in text:
 if char == ' ':
 continue
 result += char
print(result) # Hello,World!Howareyou?

五、对多个字符串批量去空格

如果你需要对一个列表或多行文本批量去空格,可以结合 map() 或列表推导式。

示例:

lines = [" Hello, World! ", " Python Programming "]
stripped_lines = [line.strip() for line in lines]
print(stripped_lines) # 输出: ['Hello, World!', 'Python Programming']

或者使用 map()

lines = [" Hello, World! ", " Python Programming "]
stripped_lines = list(map(str.strip, lines))
print(stripped_lines) # 输出: ['Hello, World!', 'Python Programming']

六、不同场景下的选择

  1. 只去除两端空格: 使用 strip()lstrip()rstrip()
  2. 去除所有空格(包括中间的空格): 使用 replace(" ", "") 或正则表达式 re.sub(r"\s+", "")
  3. 遍历的方式:  split() + join() 或for循环
  4. 批量处理: 使用列表推导式或 map()

根据实际需求,选择最适合的姿势。

哈哈!有用的姿势又增加了~~~///(^v^)\\\~~~

免费征集 | 自动化需求

还在为重复性工作头疼?数据处理耗时过长?
我们正在免费征集 自动化需求,无论是文件整理、报表生成、邮件处理还是网页爬取,只要您有需求,我愿意免费为您编写脚本,让繁琐任务一键完成!


? 我们能帮您做什么?

  • 文件处理:批量重命名、分类归档、数据清洗。
  • 数据处理:Excel 自动化、报表生成、跨平台同步。
  • 网页爬取:自动获取产品信息、市场数据或文章内容
  • 邮件管理:自动发送邮件、下载附件、分类归档。
  • 日常任务:自动安排日程、提醒任务、同步到项目管理工具。
  • 其他需求:只要您想到的,我们都愿意尝试!

? 如何提交需求?

  1. CSDN私信或直接留言。

立即行动,释放您的生产力!

作者:游客520原文地址:https://blog.csdn.net/weixin_42238129/article/details/144363516

%s 个评论

要回复文章请先登录注册