【Python Cookbook】S02E10 从字符串中去除不需要的字符

问题

如果我们希望能够从字符串的开始、结尾或中间部分去掉指定的字符,应该怎么办?

解决方案

Python 字符串内置函数 strip() 方法可以同时从字符串的开头和结尾部分去除指定字符。lstrip() 方法则可以从字符串的左侧去除指定字符,同理 rstrip()

当三个 strip() 函数参数为空时,默认去除空格符。

text = " hello world \n "

print(text.strip())
print(text.lstrip())
print(text.rstrip())

结果:

hello world
hello world \n
 hello world

当指定参数内容时,则去除指定位置的指定内容:

text = "------hello======"

print(text.strip("-="))
print(text.lstrip("-"))
print(text.rstrip("="))

结果:

hello
hello======
------hello

讨论

然而 strip() 方法除了可以对字符串的开头和结尾做处理外,是无法对其中的内容做处理的。此时,我们应当选择使用 replace() 方法以及 re.sub() 方法。

import  re

text = " hello  wo rld"
# replace() 方法
print(text.replace(" ", ""))
# re.sub() 方法
print(re.sub('\s+', '', text))

结果:

helloworld
helloworld

在更多的场景下,我们可以将 strip() 函数与生成器表达式相结合,这种方式最大的有点在于其高效,且没有将数据读取到任何形式的临时列表中。

相关推荐

  1. 字符串星号

    2024-06-07 19:14:07       38 阅读
  2. LeetCode 2710.移字符串尾随零

    2024-06-07 19:14:07       21 阅读
  3. LeetCode 2707. 字符串额外字符

    2024-06-07 19:14:07       43 阅读
  4. Python——用新字符替换字符串字符

    2024-06-07 19:14:07       9 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-07 19:14:07       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-07 19:14:07       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-07 19:14:07       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-07 19:14:07       20 阅读

热门阅读

  1. adb 常用命令

    2024-06-07 19:14:07       10 阅读
  2. 鸿蒙emitter 订阅事件封装 EmitterUtils

    2024-06-07 19:14:07       10 阅读
  3. git常用命令

    2024-06-07 19:14:07       8 阅读
  4. 自己实现一个Feign

    2024-06-07 19:14:07       11 阅读
  5. Random —— python(And)numpy

    2024-06-07 19:14:07       8 阅读
  6. D365 子窗体调用父窗体方法

    2024-06-07 19:14:07       10 阅读
  7. PyTorch交叉熵理解

    2024-06-07 19:14:07       10 阅读
  8. Python—面向对象小解(4)--模块介绍

    2024-06-07 19:14:07       9 阅读
  9. 【MyBatisPlus】MyBatisPlus介绍与使用

    2024-06-07 19:14:07       9 阅读
  10. 基于python的宠物商店管理系统部署步骤

    2024-06-07 19:14:07       10 阅读
  11. 力扣算法题:多数元素 --多语言实现

    2024-06-07 19:14:07       8 阅读
  12. golang标准库错误处理及自定义错误处理示例

    2024-06-07 19:14:07       9 阅读