Python 去除字符串中指定字符串


Posted in Python onMarch 05, 2020

1、背景

最近的项目中,再次踩到Python字符串处理的坑,决定把此次解决方案记录一下,以勿踩坑。

2、遇到坑

原本字符串:大坪英利国际8号楼88-88号重庆汉乔科技有限公司大坪英利国际8号楼
去除最左边的字符串:大坪英利国际8号楼
预期结果:88-88号重庆汉乔科技有限公司大坪英利国际8号楼

自然而然,第一个想到的就是lstrip()函数。

Python中lstrip() 方法用于截掉字符串左边的空格或指定字符。
但实际上结果:

lstrip: -88号重庆汉乔科技有限公司大坪英利国际8号楼

3、找到 lstrip() 坑的真相

函数原型:

def lstrip(self, chars=None): # real signature unknown; restored from __doc__
  """
  S.lstrip([chars]) -> str
  
  Return a copy of the string S with leading whitespace removed.
  If chars is given and not None, remove characters in chars instead.
  """
  return ""

看来 lstrip 方法是 比对字符 并去除,而不是简单的去除最左边字符串。
那好,再验证一下:

"重庆重庆师范大学".lstrip("重庆")

结果:

师范大学

那我想简单的去除字符串中的首个指定字符串,最好不用 lstrip() 了。
于是又想到了split 方法 和 replace 方法……

4、解决方案

4.1、方法1 split

函数原型:

def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False):
  """
  Generator method to split a string using the given expression as a separator.
  May be called with optional C{maxsplit} argument, to limit the number of splits;
  and the optional C{includeSeparators} argument (default=C{False}), if the separating
  matching text should be included in the split results.
  
  Example::    
    punc = oneOf(list(".,;:/-!?"))
    print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
  prints::
    ['This', ' this', '', ' this sentence', ' is badly punctuated', '']
  """
  splits = 0
  last = 0
  for t,s,e in self.scanString(instring, maxMatches=maxsplit):
    yield instring[last:s]
    if includeSeparators:
      yield t[0]
    last = e
  yield instring[last:]

4.2、方法2 replace

函数原型:

def replace(self, old, new, count=None):
  """
  For each element in `self`, return a copy of the string with all
  occurrences of substring `old` replaced by `new`.

  See also
  --------
  char.replace

  """
  return asarray(replace(self, old, new, count))

5、案例

5.1、源代码

# -*- coding: utf-8 -*-
"""
Author: ZhenYuSha
CreateTime: 2020-2-26
Info: 去除字符串中 首个指定字符串
"""


def run(source, key):
  tmp_ls = source.lstrip(key)
  tmp_re = source.replace(key, "", 1)
  tmp_sp = source.split(key, 1)[1]
  return tmp_ls, tmp_re, tmp_sp


if __name__ == '__main__':
  tmp_1, tmp_2, tmp_3 = run("大坪英利国际8号楼88-88号重庆汉乔科技有限公司大坪英利国际8号楼", "大坪英利国际8号楼")
  print("test_1 lstrip:", tmp_1)
  print("test_1 replace:", tmp_2)
  print("test_1 split:", tmp_3)

  tmp_1, tmp_2, tmp_3 = run("重庆重庆师范大学", "重庆")
  print("test_2 lstrip:", tmp_1)
  print("test_2 replace:", tmp_2)
  print("test_2 split:", tmp_3)

5.2、效果

Python 去除字符串中指定字符串

6、延伸

split 和 replace 可以解决字符串首个指定字符串去除问题, 但去除字符串这个问题不仅仅是去除就完了,还要去判断是否符合我们的要求。

6.1、看字符串开头是否是指定字符串

如果需要以指定字符串开头,要用 startswith 函数来判断。

6.2、看字符串中是否存在指定字符串

如果不存在指定字符串,直接用 split 和 replace 会直接崩溃的,那就需要 find 函数来查看了。

到此这篇关于Python 去除字符串中指定字符串的文章就介绍到这了,更多相关Python 去除字符串 内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python subprocess 杀掉全部派生的子进程方法
Jan 16 Python
Python日期时间对象转换为字符串的实例
Jun 22 Python
一行代码让 Python 的运行速度提高100倍
Oct 08 Python
pandas筛选某列出现编码错误的解决方法
Nov 07 Python
python+selenium实现QQ邮箱自动发送功能
Jan 23 Python
python 将日期戳(五位数时间)转换为标准时间
Jul 11 Python
详解Python3 pandas.merge用法
Sep 05 Python
Python大数据之网络爬虫的post请求、get请求区别实例分析
Nov 16 Python
Django2 连接MySQL及model测试实例分析
Dec 10 Python
Python hashlib加密模块常用方法解析
Dec 18 Python
使用python turtle画高达
Jan 19 Python
pandas和spark dataframe互相转换实例详解
Feb 18 Python
Python脚本去除文件的只读性操作
Mar 05 #Python
Python IDE环境之 新版Pycharm安装详细教程
Mar 05 #Python
Python Handler处理器和自定义Opener原理详解
Mar 05 #Python
Python使用进程Process模块管理资源
Mar 05 #Python
Python json模块与jsonpath模块区别详解
Mar 05 #Python
Python如何用filter函数筛选数据
Mar 05 #Python
Python API len函数操作过程解析
Mar 05 #Python
You might like
php4与php5的区别小结(配置异同)
2011/12/20 PHP
关于JSON以及JSON在PHP中的应用技巧
2013/11/27 PHP
Symfony核心类概述
2016/03/17 PHP
DWZ+ThinkPHP开发时遇到的问题分析
2016/12/12 PHP
PHP实现QQ、微信和支付宝三合一收款码实例代码
2018/02/19 PHP
PhpStorm2020.1 安装 debug - Postman 调用的详细教程
2020/08/17 PHP
JavaScript生成GUID的多种算法小结
2013/08/18 Javascript
关于JavaScript命名空间的一些心得
2014/06/07 Javascript
浅析Node.js中的内存泄漏问题
2015/06/23 Javascript
基于JS实现回到页面顶部的五种写法(从实现到增强)
2016/09/03 Javascript
JavaScript仿网易选项卡制作代码
2016/10/06 Javascript
自动适应iframe右边的高度
2016/12/22 Javascript
详解AngularJS通过ocLazyLoad实现动态(懒)加载模块和依赖
2017/03/01 Javascript
TypeScript入门-接口
2017/03/30 Javascript
BootStrap Select清除选中的状态恢复默认状态
2017/06/20 Javascript
微信小程序实现炫酷的弹出式菜单特效
2019/01/28 Javascript
使用element-ui table expand展开行实现手风琴效果
2019/03/15 Javascript
vue操作动画的记录animate.css实例代码
2019/04/26 Javascript
在layui中select更改后生效的方法
2019/09/05 Javascript
非常漂亮的js烟花效果
2020/03/10 Javascript
node.js 如何监视文件变化
2020/09/01 Javascript
django批量导入xml数据
2016/10/16 Python
Python 经典算法100及解析(小结)
2019/09/13 Python
tensorflow从ckpt和从.pb文件读取变量的值方式
2020/05/26 Python
CSS3中伪元素::before和::after的用法示例
2017/09/18 HTML / CSS
小米旗下精品生活电商平台:小米有品
2018/12/18 全球购物
荷兰度假屋租赁网站:Aan Zee
2020/02/28 全球购物
行政文员岗位职责
2013/11/08 职场文书
策划主管的工作职责
2013/11/24 职场文书
八项规定个人对照检查材料思想汇报
2014/09/25 职场文书
群众路线个人对照检查材料2014
2014/09/26 职场文书
2014年财务人员工作总结
2014/11/11 职场文书
2014年售后服务工作总结
2014/11/18 职场文书
2016孝老爱亲模范事迹材料
2016/02/26 职场文书
导游词之河姆渡遗址博物馆
2019/10/10 职场文书
CSS3实现的文字弹出特效
2021/04/16 HTML / CSS