前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 去除字符串中指定字符串

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

作者头像
砸漏
发布2020-11-05 10:07:05
1.7K0
发布2020-11-05 10:07:05
举报
文章被收录于专栏:恩蓝脚本恩蓝脚本

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、效果

6、延伸

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

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

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

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

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

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档