Python如何消除字符串前后中间的空白
(这里不使用正则表达式非常适合小白)
相信这是很多人都会遇到的一个小问题。其实要是只想消除前后的空白。我们知道在C/C++语言中只需要将字符串数组进行遍历,遇到非字母的值直接剔除即可。那么python要怎么做呢?
strip, lstrip, rstrip
python提供了3个函数用于剔除字符。
strip(char)是可以剔除两端的指定字符。
lstrip(char)是可以剔除左端的指定字符。
rstrip(char)是可以剔除右端的指定字符。
用法如下:
content = " abc def ghi "
content = content.strip(" ")
replace
python提供了一个replace函数用于字符的替换
replace(old, new)将old字符串替换成new的字符串
用法如下:
content = " abc def ghi "
content = content.replace(" ", " ")
组合剔除
但是上面两种方法都有弊端,strip方法只能剔除两端的空格,而replace又只能更换指定长度的空格,当连续空格数量远远大于两个的时候,经过一次replace并不能完全剔除干净。
因此我们自己实现一个函数:
def replaceAll(old: str, new: str, sentence: str):
while sentence.find(old) > -1:
sentence = sentence.replace(old, new)
return sentence
def clearAllBlank(sentence: str):
sentence = replaceAll(" ", " ", sentence)
sentence = sentence.strip()
return sentence
def clearAllBlankCh(sentence: str):
sentence = replaceAll(" ", "", sentence)
sentence = sentence.strip()
return sentence
context = " hello world nice ok done "
context2 = " 这是 一 坨 汉字,怎么 解决 "
context = clearAllBlank(context)
context2 = clearAllBlankCh(context2)
print(context + ";")
print(context2 + ';')
本文介绍了Python中去除字符串前后及中间空白的方法,包括strip、lstrip和rstrip函数以及replace方法。通过实例展示了如何利用这些函数有效清理字符串中的多余空格,并提供了一个自定义函数replaceAll来组合使用这些方法,确保彻底清除所有空格。最后,展示了在实际字符串清理中的应用案例。
422

被折叠的 条评论
为什么被折叠?



