Python去除字符串空格的常用方法详解

Elena
Elena
发布时间:2026-10-15 | 4人浏览过
原创

本文介绍Python中去除字符串空格的多种常用方式。包括使用lstrip()、rstrip()和strip()分别处理左侧、右侧及两侧空格;利用replace()将空格替换为空;通过正则表达式re.sub()移除所有空白字符;以及结合split()和join()方法的高效实现。

前言

在处理字符串数据时,经常需要定制化的方式去除无用的空格。Python提供了多种内置方法或借助正则表达式来实现这一需求。

1. 去除左侧空格

string = "  * it is blank space test *  "
print (string.lstrip())

result:
* it is blank space test *  

2. 去除右侧空格

string = "  * it is blank space test *  "
print (string.rstrip())

result:
  * it is blank space test *

3. 去除左右两侧空格

string = "  * it is blank space test *  "
print (string.strip())

result:
* it is blank space test *

4. 去除所有空格

实现去除所有空格主要有以下几种方式。

示例1:调用字符串的replace()方法,将空格字符替换为空字符串。

string = "  * it is blank space test *  "
str_new = string.replace(" ", "")
print str_new

result:
*itisblankspacetest*

示例2:使用正则表达式匹配空格并替换为空。

import re

string = "  * it is blank space test *  "
str_new = re.sub(r"\s+", "", string)
print str_new

result:
*itisblankspacetest*

示例3:结合使用join()和split()方法。

该方法可以有效去除字符串中的所有空格。

其中,join()用于将字符串列表合成一个字符串,split()用于按规则分割字符串。

>>> a = " a b c "
 
>>> b = a.split()  # 字符串按空格分割成列表
 
>>> b ['a', 'b', 'c']
 
>>> c = "".join(b) # 使用一个空字符串合成列表内容生成新的字符串
 
>>> c 'abc'
 
 
 
# 快捷用法
 
>>> a = " a b c "
 
>>> "".join(a.split())
 
'abc'

总结

本文介绍了Python中去除空格的几种常用方式。如需了解更多相关内容,可搜索本站历史文章或继续阅读后续教程。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表