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入门_浅谈数据结构的4种基本类型
May 16 Python
Python 加密的实例详解
Oct 09 Python
python 判断参数为Nonetype类型或空的实例
Oct 30 Python
详解Python基础random模块随机数的生成
Mar 23 Python
使用 Python 玩转 GitHub 的贡献板(推荐)
Apr 04 Python
Python中查看变量的类型内存地址所占字节的大小
Jun 26 Python
python从zip中删除指定后缀文件(推荐)
Dec 05 Python
numpy ndarray 取出满足特定条件的某些行实例
Dec 05 Python
关于numpy.where()函数 返回值的解释
Dec 06 Python
浅谈tf.train.Saver()与tf.train.import_meta_graph的要点
May 26 Python
Python使用OpenCV实现虚拟缩放效果
Feb 28 Python
python opencv将多个图放在一个窗口的实例详解
Feb 28 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
如何在PHP中使用Oracle数据库(6)
2006/10/09 PHP
一些被忽视的PHP函数(简单整理)
2010/04/30 PHP
php错误级别的设置方法
2013/06/17 PHP
解析PHP计算页面执行时间的实现代码
2013/06/18 PHP
yii2整合百度编辑器umeditor及umeditor图片上传问题的解决办法
2016/04/20 PHP
php 中奖概率算法实现代码
2017/01/25 PHP
PHP弱类型语言中类型判断操作实例详解
2017/08/10 PHP
IE网页js语法错误2行字符1、FF中正常的解决方法
2013/09/09 Javascript
面向对象设计模式的核心法则
2013/11/10 Javascript
jquery live()调用不存在的解决方法
2014/02/26 Javascript
jquery插件hiAlert实现网页对话框美化
2015/05/03 Javascript
JS实现含有中文字符串的友好截取功能分析
2017/03/13 Javascript
Angualrjs 表单验证的两种方式(失去焦点验证和点击提交验证)
2017/05/09 Javascript
vue父组件中获取子组件中的数据(实例讲解)
2017/09/27 Javascript
深入掌握 react的 setState的工作机制
2017/09/27 Javascript
JavaScript原生实现观察者模式的示例
2017/12/15 Javascript
解决layui的radio属性或别的属性没显示出来的问题
2019/09/26 Javascript
vue print.js打印支持Echarts图表操作
2020/11/13 Javascript
如何使用RoughViz可视化Vue.js中的草绘图表
2021/01/30 Vue.js
[02:19]2014DOTA2国际邀请赛 专访820少年们一起去追梦吧
2014/07/14 DOTA
python命令行参数解析OptionParser类用法实例
2014/10/09 Python
简单谈谈python中的多进程
2016/11/06 Python
Python实现的HMacMD5加密算法示例
2018/04/03 Python
python中pip的安装与使用教程
2018/08/10 Python
Python基于Twilio及腾讯云实现国际国内短信接口
2020/06/18 Python
如何用 Python 制作 GitHub 消息助手
2021/02/20 Python
柒牌官方商城:中国男装优秀品牌
2017/06/30 全球购物
Swanson中国官网:美国斯旺森健康产品公司
2021/03/01 全球购物
怎么写好自荐信
2013/10/30 职场文书
应届大学毕业生找工作的求职信范文
2013/11/29 职场文书
中学生差生评语
2014/01/30 职场文书
集中采购方案
2014/06/10 职场文书
2014年基层党支部工作总结
2014/12/04 职场文书
教学工作总结范文5篇
2019/08/19 职场文书
Python控制台输出俄罗斯方块移动和旋转功能
2021/04/18 Python
MySQL中正则表达式(REGEXP)使用详解
2022/07/07 MySQL