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 sentencedef clearAllBlank(sentence: str):sentence = replaceAll(" ", " ", sentence)sentence = sentence.strip()return sentencedef clearAllBlankCh(sentence: str):sentence = replaceAll(" ", "", sentence)sentence = sentence.strip()return sentencecontext = " hello world nice ok done "
context2 = " 这是 一 坨 汉字,怎么 解决 "context = clearAllBlank(context)
context2 = clearAllBlankCh(context2)print(context + ";")
print(context2 + ';')