Remove the string of Python developers in the first specified string

1. Background

Recent project, again stepped pit Python string handling, decided to record what the solution, do not step on to the pit.

2, encountered pit

Originally string: Taping Yingli International Building 8, No. 88-88 Hanqiao Ke Technology Co., Ltd. Chongqing Daping Yingli International Building 8,
remove the string leftmost: Daping Yingli International Building 8
Expected results: No. 88-88 Chongqing Han Qiaoke technology Ltd. Daping Yingli international Building 8

Naturally, the first thought is lstrip () function.

In the lstrip Python () method is used or a specified character string truncated space left.
But in fact the result of:

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

Truth 3, find lstrip () pit

Prototype:

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 ""

It seems lstrip method is to compare character and removed, rather than simply removing the leftmost string.
Well, then verify:

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

result:

师范大学

I want a simple string in the first removal of the specified string, not the best lstrip () a.
So I thought of the split method and replace the method ......

4. Solution

4.1 Method 1 split

Prototype:

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, Method 2 replace

Prototype:

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, case

5.1 source code

# -*- 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, the effect

Here Insert Picture Description

6, extends

split and replace strings can solve the problem of removing the first specified string, but the string to remove this issue is not just the removal would be finished, but also to determine compliance with our requirements.

6.1, see the beginning of the string is specified string

If you need to start with a specified string, use startswith function to determine.

6.2, to see whether there is a specified string string

If the specified string does not exist, the direct use of split and will directly replace crash, it would need to find a function to see.

Published 263 original articles · won praise 757 · Views 2.29 million +

Guess you like

Origin blog.csdn.net/u014597198/article/details/104511575