記事のディレクトリ
1.背景
最近のプロジェクトでは、溶液は、ピットへステップしていないものを記録することを決め、再びステップピットPythonの文字列処理、。
2、遭遇したピット
もともと文字列:第88から88 Hanqiao柯技術有限公司重慶大坪英利綠色能源国際ビル8、テーピング英利綠色能源国際ビル8、
大坪英利綠色能源国際ビル8:文字列の左端を削除
期待される結果:第88から88重慶漢Qiaoke技術(株)大坪英利綠色能源国際ビル8
当然のことながら、最初に考えたlstrip()関数です。
lstripではPythonの()メソッドが使用されているか、指定した文字列切り捨てスペースを残しました。
しかし、実際に結果:
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()します。
だから私は、分割方法を考えや方法を置き換える......
4.ソリューション
4.1方法1スプリット
プロトタイプ:
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置き換えます
プロトタイプ:
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に示すように、延びています
スプリットと置き換える文字列が最初に指定した文字列を除去する問題を解決することができますが、この問題を除去するための文字列がちょうど除去が終了されるだろうが、また、私たちの要求事項の遵守を決定することではありません。
6.1は、文字列の先頭が指定された文字列を参照してください
あなたが指定した文字列で開始する必要がある場合は、使用しSTARTSWITH機能が決定します。
6.2、指定された文字列の文字列があるかどうかを確認するには
指定された文字列は、分割を直接使用存在しておらず、直接クラッシュを交換する場合は、それが参照する機能を見つける必要があります。