在 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']
六、不同场景下的选择
只去除两端空格: 使用 strip()、lstrip() 或 rstrip()。
去除所有空格(包括中间的空格): 使用 replace(" ", "") 或正则表达式 re.sub(r"\s+", "")。
遍历的方式: split() + join() 或for循环
批量处理: 使用列表推导式或 map()。
根据实际需求,选择最适合的姿势。
以上就是python中字符串去空格的五种方法介绍与对比的详细内容,更多关于python字符串去空格的资料请关注代码网其它相关文章!
发表评论