Python之去掉字符串空格(strip)
发布日期:2021-06-03 08:57:45 浏览次数:14 分类:技术文章

本文共 999 字,大约阅读时间需要 3 分钟。


正文:


Python去掉字符串空格有三个函数:


strip 同时去掉字符串左右两边的空格;lstrip 去掉字符串左边的空格;rstrip 去掉字符串右边(末尾)的空格;

详细解读:


声明:s为字符串,re为要删除的字符序列

  • strip函数:s.strip(re)
    1,用于删除s字符串中开头处、结尾处、位于re删除序列的字符
    2,当re为空时,strip()默认是删除空白符(包括‘\n’,‘\r’,‘\t’,‘’),例如:
>>>a = '    abc'>>>a.strip()'abc'>>>a = '\t\t\nabc'>>>a.strip()'abc'>>>a = '  abc\r\t'>>>a.strip()'abc'

3,这里我们说的re删除序列是只要满足re的开头或者结尾上的字符在删除序列内,就能删除掉,比如说:

>>> a = 'abc123'>>>>a.strip('342')'abc1'>>>a.strip('234')'abc1'

可以看出结果是一样的。

  • lstrip函数:s.lstrip(re),用于删除s字符串中开头处,位于re删除序列中的字符,比如:
>>>a = "    this is string example.....wow!!!   ">>>a.lstrip()'this is string example.....wow!!!   '>>>a = "88888888this is string example....wow!!!8888888">>>a.lstrip('8')'this is string example....wow!!!8888888'
  • rstrip函数:s.rstrip(re),用于删除s字符串中结尾处,位于re删除序列的字符,比如:
>>>a = "    this is string example.....wow!!!   ">>>a.rstrip()'    this is string example.....wow!!!'>>>a = "88888888this is string example....wow!!!8888888">>>a.rstrip('8')'8888888this is string example....wow!!!'

OK!到此结束啦,不知道你了解了没???^-^

转载地址:https://blog.csdn.net/HuaCode/article/details/79942237 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:C++类的构造函数与析构函数
下一篇:TypeError: unhashable type: 'dict'

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月07日 10时44分14秒