栏目分类:
子分类:
返回
终身学习网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
终身学习网 > IT > 软件开发 > 后端开发 > Python

Python学习笔记(6): 如何消除字符串前后中间的空白

Python 更新时间:发布时间: 百科书网 趣学号
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 + ';')
转载请注明:文章转载自 www.051e.com
本文地址:http://www.051e.com/it/925514.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 ©2023-2025 051e.com

ICP备案号:京ICP备12030808号