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 通过pip安装Django详细介绍
Apr 28 Python
numpy中索引和切片详解
Dec 15 Python
python numpy格式化打印的实例
May 14 Python
python 查找文件名包含指定字符串的方法
Jun 05 Python
Python从ZabbixAPI获取信息及实现Zabbix-API 监控的方法
Sep 17 Python
用Python实现大文本文件切割的方法
Jan 12 Python
使用jupyter notebook将文件保存为Markdown,HTML等文件格式
Apr 14 Python
Python3.7在anaconda里面使用IDLE编译器的步骤详解
Apr 29 Python
浅谈Python中的字符串
Jun 10 Python
python两个list[]相加的实现方法
Sep 23 Python
地图可视化神器kepler.gl python接口的使用方法
Dec 22 Python
自己搭建resnet18网络并加载torchvision自带权重的操作
May 13 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删除数组中重复元素的方法
2015/12/22 PHP
[原创]PHP获取数组表示的路径方法分析【数组转字符串】
2017/09/01 PHP
解决PHP使用CURL发送GET请求时传递参数的问题
2019/10/11 PHP
解密效果
2006/06/23 Javascript
经典的带阴影的可拖动的浮动层
2006/06/26 Javascript
获取任意Html元素与body之间的偏移距离 offsetTop、offsetLeft (For:IE5+ FF1 )[
2006/12/22 Javascript
Add a Picture to a Microsoft Word Document
2007/06/15 Javascript
JQuery select标签操作代码段
2010/05/16 Javascript
JS 树形递归实例代码
2010/05/18 Javascript
判断js对象是否拥有某一个属性的js代码
2013/08/16 Javascript
纯js分页代码(简洁实用)
2013/11/05 Javascript
jQuery操作Select的Option上下移动及移除添加等等
2013/11/18 Javascript
node.js中的socket.io的广播消息
2014/12/15 Javascript
深入理解JavaScript系列(42):设计模式之原型模式详解
2015/03/04 Javascript
jQuery实现的进度条效果
2015/07/15 Javascript
解决nodejs的npm命令无反应的问题
2018/05/17 NodeJs
Vue.js 中的实用工具方法【推荐】
2019/07/04 Javascript
python练习程序批量修改文件名
2014/01/16 Python
Python 多线程抓取图片效率对比
2016/02/27 Python
Python正则表达式教程之三:贪婪/非贪婪特性
2017/03/02 Python
Python简单生成随机数的方法示例
2018/03/31 Python
详解Django中间件的5种自定义方法
2018/07/26 Python
基于tf.shape(tensor)和tensor.shape()的区别说明
2020/06/30 Python
通过实例了解Python异常处理机制底层实现
2020/07/23 Python
Shopee印度尼西亚:东南亚与台湾市场最大电商平台
2018/06/17 全球购物
MediaMarkt比利时:欧洲最大电器连锁店
2020/12/21 全球购物
迪士尼法国在线商店:shopDisney FR
2020/12/03 全球购物
财务会计专业应届毕业生求职信
2013/10/18 职场文书
美德少年事迹材料
2014/01/23 职场文书
慈善献爱心倡议书
2015/04/27 职场文书
文明旅游倡议书
2015/04/28 职场文书
2015年电教工作总结
2015/05/26 职场文书
关爱空巢老人感想
2015/08/11 职场文书
Python函数式编程中itertools模块详解
2021/09/15 Python
Python语言中的数据类型-序列
2022/02/24 Python
基于PyQt5制作一个群发邮件工具
2022/04/08 Python